Java 获取集合长度
生活随笔
收集整理的這篇文章主要介紹了
Java 获取集合长度
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
使用 Collections 類 的collection.add() 來添加數(shù)據(jù)并使用 collection.size()來計算集合的長度
完整代碼
import java.util.*;public class Main {public static void main(String [] args) { System.out.println( "集合實(shí)例!\n" ); int size;HashSet collection = new HashSet ();String str1 = "Yellow", str2 = "White", str3 = "Green", str4 = "Blue"; Iterator iterator;collection.add(str1); collection.add(str2); collection.add(str3); collection.add(str4);System.out.print("集合數(shù)據(jù): "); iterator = collection.iterator(); while (iterator.hasNext()){System.out.print(iterator.next() + " "); }System.out.println();size = collection.size();if (collection.isEmpty()){System.out.println("集合是空的");}else{System.out.println( "集合長度: " + size);}System.out.println();} }結(jié)果輸出
集合實(shí)例!集合數(shù)據(jù): White Yellow Blue Green 集合長度: 4 創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎總結(jié)
以上是生活随笔為你收集整理的Java 获取集合长度的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++ 运算符重载规则
- 下一篇: Java访问对象的属性和行为