當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。