Java ArrayBlockingQueue toString()方法

Java ArrayBlockingQueue toString()方法

ArrayBlockingQueue 类的 toString() 方法是用来获得ArrayBlockingQueue对象的字符串表示。ArrayBlockingQueue的字符串包含了ArrayBlockingQueue的元素,按照从头(head)到尾(tail)的顺序,用方括号(”[]“)括起来。这些元素被字符”,”(逗号和空格)分开。所以基本上toString()方法是用来把ArrayBlockingQueue的所有元素转换成一个字符串。

语法

public String toString()

返回值: 该方法返回ArrayBlockingQueue的一个字符串表示。

下面的程序说明了ArrayBlockingQueue类的toString()方法。

程序1 :

// Program to demonstrate how to apply toString() method
// of ArrayBlockingQueue Class.
  
import java.util.concurrent.ArrayBlockingQueue;
  
  
public class GFG {
  
public static void main(String[] args) {
    // Define capacity of ArrayBlockingQueue
    int capacity = 5;
      
    // Create object of ArrayBlockingQueue
    ArrayBlockingQueue<Integer> queue = 
        new ArrayBlockingQueue<Integer>(capacity);
      
    // Add 5 elements to ArrayBlockingQueue
    queue.offer(423);
    queue.offer(422);
    queue.offer(421);
    queue.offer(420);
    queue.offer(424);
      
    // Print queue
    System.out.println("Queue is "+queue);
      
    // Call toString() method and Create an iterator
    String stringRepresentation=queue.toString();
      
    // Print String value returned by toString() method
    System.out.println("\nThe String returned by toString():");
    System.out.println(stringRepresentation);
      
      
    } 
}

输出。

Queue is [423, 422, 421, 420, 424]

The String returned by toString():
[423, 422, 421, 420, 424]

程序 2:

// Program Demonstrate how to apply toString() method
// of ArrayBlockingQueue Class.
  
import java.util.concurrent.ArrayBlockingQueue;
  
  
public class GFG {
  
public static void main(String[] args) {
    // Define capacity of ArrayBlockingQueue
    int capacity = 10;
      
    // Create object of ArrayBlockingQueue
    ArrayBlockingQueue<String> queue = 
                    new ArrayBlockingQueue<String>(capacity);
        
    // Add 5 elements to ArrayBlockingQueue
    queue.offer("User");
    queue.offer("Employee");
    queue.offer("Manager");
    queue.offer("Analyst");
    queue.offer("HR");
    queue.offer("Tester");
      
    // Print queue
    System.out.println("Queue is "+queue);
      
    // Call toString() method and Create an iterator
    String stringRepresentation=queue.toString();
      
    // Print String value returned by toString() method
    System.out.println("\nThe String returned by toString():");
    System.out.println(stringRepresentation);
      
      
    } 
}

输出。

Queue is [User, Employee, Manager, Analyst, HR, Tester]

The String returned by toString():
[User, Employee, Manager, Analyst, HR, Tester]

参考资料: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ArrayBlockingQueue.html#toString

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程