Java LinkedBlockingQueue toString()方法示例

Java LinkedBlockingQueue toString()方法示例

LinkedBlockingQueue的 toString() 方法返回一个向量的字符串表示形式,向量包含其元素从第一个元素(head)到最后一个元素(tail),用方括号(“[]”)括起来,按顺序排列。元素之间由逗号和空格字符‘, ’分隔。因此,toString()方法用于将LinkedBlockingQueue的所有元素转换为字符串表示形式。

该方法在类 **AbstractCollection ** 中覆盖toString()方法。

语法:

public String toString()

返回值: 该方法返回一个字符串,表示从第一个元素(head)到最后一个元素(tail)的LinkedBlockingQueue的元素,并用方括号(“[]”)括起来,用‘, ’(逗号和空格)分隔。

下面是演示LinkedBlockingQueue类的toString()方法的程序:

程序一:

// Java程序演示LinkedBlockingQueue类的toString()方法。
  
import java.util.concurrent.LinkedBlockingQueue;
  
public class GFG {
  
    public static void main(String[] args)
    {
        //定义LinkedBlockingQueue的容量
        int capacityOfQueue = 50;
  
        //创建LinkedBlockingQueue对象
        LinkedBlockingQueue<Integer> linkedQueue
            = new LinkedBlockingQueue<Integer>(capacityOfQueue);
  
        //添加元素到LinkedBlockingQueue
        linkedQueue.add(2300);
        linkedQueue.add(1322);
        linkedQueue.add(8945);
        linkedQueue.add(6512);
  
        //linkedQueue上的toString()
        String queueRepresentation = linkedQueue.toString();
  
        //打印结果
        System.out.println("Queue Representation:");
        System.out.println(queueRepresentation);
    }
}
队列表示:
[2300, 1322, 8945, 6512]
// Java程序演示LinkedBlockingQueue类的toString()方法。
  
import java.util.concurrent.LinkedBlockingQueue;
  
public class GFG {
  
    //创建一个Employee对象,其职位和薪水为属性
    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方法
    public static void main(String[] args)
    {
        GFG gfg=new GFG();
        gfg.stringRepresentation();
    }
  
    public void stringRepresentation()
    {
  
        //定义LinkedBlockingQueue的容量
        int capacity=50;
  
        //创建LinkedBlockingQueue对象
        LinkedBlockingQueue<Employee> linkedQueue
            = new LinkedBlockingQueue<Employee>(capacity);
  
        Employee emp1=new Employee("Aman","分析员","24000");
        Employee emp2=new Employee("Sachin","开发人员","39000");
  
        //添加Employee对象到linkedQueue
        linkedQueue.add(emp1);
        linkedQueue.add(emp2);
  
        //linkedQueue上的toString()
        String queueRepresentation=linkedQueue.toString();
  
        //打印结果
        System.out.println("Queue Representation:");
        System.out.println(queueRepresentation);
    }
}
队列表示法:
[员工 [姓名=Aman,职位=分析师,薪水=24000],员工 [姓名=Sachin,职位=开发者,薪水=39000]]

参考文献: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/LinkedBlockingQueue.html#toString–

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程