📜  Java中的 ArrayBlockingQueue toString() 方法

📅  最后修改于: 2022-05-13 01:54:53.095000             🧑  作者: Mango

Java中的 ArrayBlockingQueue toString() 方法

ArrayBlockingQueue类的toString()方法用于获取 ArrayBlockingQueue 对象的字符串表示形式。 ArrayBlockingQueue 的字符串包含 ArrayBlockingQueue 的元素,顺序从 first(head) 到 last(tail),用方括号(“[]”)括起来。元素由字符“、”(逗号和空格)分隔。所以基本上 toString() 方法用于将 ArrayBlockingQueue 的所有元素转换为字符串。

句法:

public String toString()

返回值:该方法返回 ArrayBlockingQueue 的字符串表示形式。

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

方案一:

// 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 queue = 
        new ArrayBlockingQueue(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]

方案二:

// 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 queue = 
                    new ArrayBlockingQueue(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: Java/util/concurrent/ArrayBlockingQueue.html#toString