当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java ArrayBlockingQueue toString()用法及代码示例


ArrayBlockingQueue类的toString()方法用于获取ArrayBlockingQueue对象的字符串表示形式。 ArrayBlockingQueue字符串包含ArrayBlockingQueue元素,从第一个(头)到最后一个(尾)的顺序包括在方括号(“[]”)中。元素由字符“,”(逗号和空格)分隔。因此,本质上使用toString()方法将ArrayBlockingQueue的所有元素转换为String。

用法:

public String toString()

返回值:该方法返回ArrayBlockingQueue的String表示形式。


以下示例程序旨在说明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



相关用法


注:本文由纯净天空筛选整理自AmanSingh2210大神的英文原创作品 ArrayBlockingQueue toString() Method in Java。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。