Java中的 LinkedBlockingQueue toString() 方法及示例
LinkedBlockingQueue 的toString()方法返回LinkedBlockingQueue元素的字符串表示形式。 LinkedBlockingQueue 的字符串包含从 first(head) 到 last(tail) 的元素,按正确的顺序括在方括号(“[]”)中。元素由字符'、'(逗号和空格)分隔。所以基本上 toString() 方法用于将 LinkedBlockingQueue 的所有元素转换为 String 表示形式。
此方法覆盖类AbstractCollection
句法:
public String toString()
返回值:该方法返回一个String,它是LinkedBlockingQueue的元素从first(head)到last(tail)的表示,按正确的顺序括在方括号(“[]”)中,用','分隔(逗号和一个空格)。
下面的程序说明了 LinkedBlockingQueue 类的 toString() 方法:
方案一:
// Java Program Demonstrate toString()
// method of LinkedBlockingQueue
import java.util.concurrent.LinkedBlockingQueue;
public class GFG {
public static void main(String[] args)
{
// define capacity of LinkedBlockingQueue
int capacityOfQueue = 50;
// create object of LinkedBlockingQueue
LinkedBlockingQueue linkedQueue
= new LinkedBlockingQueue(capacityOfQueue);
// Add element to LinkedBlockingQueue
linkedQueue.add(2300);
linkedQueue.add(1322);
linkedQueue.add(8945);
linkedQueue.add(6512);
// toString() on linkedQueue
String queueRepresentation = linkedQueue.toString();
// print results
System.out.println("Queue Representation:");
System.out.println(queueRepresentation);
}
}
输出:
Queue Representation:
[2300, 1322, 8945, 6512]
// Java Program Demonstrate toString()
// method of LinkedBlockingQueue.
import java.util.concurrent.LinkedBlockingQueue;
public class GFG {
// create an Employee Object with
// position and salary as an attribute
public class Employee {
public String name;
public String position;
public String salary;
Employee(String name, String position, String salary)
{
this.name = name;
this.position = position;
this.salary = salary;
}
@Override
public String toString()
{
return "Employee [name=" + name + ", position="
+ position + ", salary=" + salary + "]";
}
}
// Main Method
public static void main(String[] args)
{
GFG gfg = new GFG();
gfg.stringRepresentation();
}
public void stringRepresentation()
{
// define capacity of LinkedBlockingQueue
int capacity = 50;
// create object of LinkedBlockingQueue
LinkedBlockingQueue linkedQueue
= new LinkedBlockingQueue(capacity);
Employee emp1 = new Employee("Aman", "Analyst", "24000");
Employee emp2 = new Employee("Sachin", "Developer", "39000");
// Add Employee Objects to linkedQueue
linkedQueue.add(emp1);
linkedQueue.add(emp2);
// toString() on linkedQueue
String queueRepresentation = linkedQueue.toString();
// print results
System.out.println("Queue Representation:");
System.out.println(queueRepresentation);
}
}
输出:
Queue Representation:
[Employee [name=Aman, position=Analyst, salary=24000], Employee [name=Sachin, position=Developer, salary=39000]]
参考: https: Java/util/concurrent/LinkedBlockingQueue.html#toString–