Java中的ConcurrentLinkedQueue size()方法
ConcurrentLinkedQueue 类的 size() 方法用于返回此ConcurrentLinkedQueue包含的元素数。
语法:
public int size()
返回值: 此方法返回ConcurrentLinkedQueue中的元素数。
下面的程序说明了ConcurrentLinkedQueue的size()方法:
示例1:
// Java程序演示ConcurrentLinkedQueue的size()方法
import java.util.concurrent.*;
public class GFG {
public static void main(String[] args) {
// 创建ConcurrentLinkedQueue
ConcurrentLinkedQueue<Integer>
queue = new ConcurrentLinkedQueue<Integer>();
// 将数字添加到队列中
queue.add(4353);
queue.add(7824);
queue.add(78249);
queue.add(8724);
// 显示现有的ConcurrentLinkedQueue
System.out.println("ConcurrentLinkedQueue:" + queue);
// 应用size()
int size = queue.size();
// 应用size方法后打印
System.out.println("ConcurrentLinkedQueue的大小:" + size);
}
}
ConcurrentLinkedQueue: [4353, 7824, 78249, 8724]
ConcurrentLinkedQueue的大小:4
示例2:
// Java程序演示ConcurrentLinkedQueue的size()方法
import java.util.concurrent.*;
public class GFG {
public static void main(String[] args) {
// 创建ConcurrentLinkedQueue
ConcurrentLinkedQueue<String>
queue = new ConcurrentLinkedQueue<String>();
// 将字符串添加到队列中
queue.add("Aman");
queue.add("Amar");
queue.add("Sanjeet");
queue.add("Rabi");
// 显示现有的ConcurrentLinkedQueue
System.out.println("ConcurrentLinkedQueue:" + queue);
// 应用size()方法
int size = queue.size();
// 应用size方法后打印
System.out.println("ConcurrentLinkedQueue的大小:" + size);
// 移除一些元素
queue.poll();
queue.poll();
// 再次获取ConcurrentLinkedQueue的大小
size = queue.size();
// 显示现有的ConcurrentLinkedQueue
System.out.println("移除2个元素后\nConcurrentLinkedQueue: " + queue);
// 应用size方法后打印
System.out.println("ConcurrentLinkedQueue的大小:" + size);
}
}
ConcurrentLinkedQueue: [Aman, Amar, Sanjeet, Rabi]
ConcurrentLinkedQueue的大小:4
移除2个元素后
ConcurrentLinkedQueue: [Sanjeet, Rabi]
ConcurrentLinkedQueue的大小:2
参考资料: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentLinkedQueue.html#size–
极客教程