Love life Love IT IT blog: https://ithelp.ithome.com.tw/users/20119569
Java - HashSet的用法
HashSet是實作Set介面的物件,Set容器中的物件都是唯一的。
所以HashSet 是一個沒有重覆元素的集合。
另外,它是由HashMap實現的,不保證元素的順序,而且HashSet允許使用 null 元素。
HashSet的元素添加方式
//向hashset中添加一個字符串 hashset.add("abc"); //向hashset中添加一個整數 hashset.add(1); //向hashset中添加一個字符 hashset.add('a'); //向hashset中添加一個數組 int[] abc={10,11,12}; hashset.add(abc); //向hashset中添加一個自定義對象 Cat cat1=new Cat("asd", 2); hashset.add(cat1);//向hashset中添加一個對象</span>
HashSet loop
Iterator it = hashset.iterator(); while(it.hasNext()) { Object obj = it.next(); if(obj instanceof Integer) { System.out.println("Integer:"+obj); } if(obj instanceof String) { System.out.println("String:"+obj); } if(obj instanceof Character) { System.out.println("Character:"+obj); } if(obj instanceof int[]) { System.out.print("int[]:"); for(int i=0;i<abc.length;i++) { System.out.print(abc[i]+" "); } } }</span>
喜欢我的文章吗?
别忘了给点支持与赞赏,让我知道创作的路上有你陪伴。
发布评论…