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


Java ConcurrentLinkedQueue size()用法及代碼示例


ConcurrentLinkedQueue的size()方法用於返回此ConcurrentLinkedQueue包含的元素數。

用法:

public int size()

返回值:此ConcurrentLinkedQueue中此元素的方法數量。


以下示例程序旨在說明ConcurrentLinkedQueue的size()方法:

示例1:

// Java Program Demonstrate size() 
// method of ConcurrentLinkedQueue 
  
import java.util.concurrent.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // create an ConcurrentLinkedQueue 
        ConcurrentLinkedQueue<Integer> 
            queue = new ConcurrentLinkedQueue<Integer>(); 
  
        // Add Numbers to queue 
        queue.add(4353); 
        queue.add(7824); 
        queue.add(78249); 
        queue.add(8724); 
  
        // Displaying the existing ConcurrentLinkedQueue 
        System.out.println("ConcurrentLinkedQueue: " + queue); 
  
        // apply size() 
        int size = queue.size(); 
  
        // print after applying size method 
        System.out.println("Size of ConcurrentLinkedQueue: " + size); 
    } 
}
輸出:
ConcurrentLinkedQueue: [4353, 7824, 78249, 8724]
Size of ConcurrentLinkedQueue: 4

示例2:

// Java Program Demonstrate size() 
// method of ConcurrentLinkedQueue 
  
import java.util.concurrent.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // create an ConcurrentLinkedQueue 
        ConcurrentLinkedQueue<String> 
            queue = new ConcurrentLinkedQueue<String>(); 
  
        // Add String to queue 
        queue.add("Aman"); 
        queue.add("Amar"); 
        queue.add("Sanjeet"); 
        queue.add("Rabi"); 
  
        // Displaying the existing ConcurrentLinkedQueue 
        System.out.println("ConcurrentLinkedQueue: " + queue); 
  
        // apply size() on queue 
        int size = queue.size(); 
  
        // print after applying size method 
        System.out.println("Size of ConcurrentLinkedQueue: "
                           + size); 
  
        // removal of some elements 
        queue.poll(); 
        queue.poll(); 
  
        // get size of ConcurrentLinkedQueue again 
        size = queue.size(); 
  
        // Displaying the existing ConcurrentLinkedQueue 
        System.out.println("After 2 removal of elements\n"
                           + "ConcurrentLinkedQueue: " + queue); 
  
        // print after applying size method 
        System.out.println("Size of ConcurrentLinkedQueue: "
                           + size); 
    } 
}
輸出:
ConcurrentLinkedQueue: [Aman, Amar, Sanjeet, Rabi]
Size of ConcurrentLinkedQueue: 4

After 2 removal of elements

ConcurrentLinkedQueue: [Sanjeet, Rabi]
Size of ConcurrentLinkedQueue: 2

參考: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentLinkedQueue.html#size–



相關用法


注:本文由純淨天空篩選整理自AmanSingh2210大神的英文原創作品 ConcurrentLinkedQueue size() method in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。