標籤:使用 元素 equals ati 中比 dem 體系 增強for迴圈 add
API中比較 set 和 collection 集合都有一樣的方法
* A:Set集合概述及特點
* 通過API查看即可
* B:案例示範
* HashSet儲存字串並遍曆
*
HashSet<String> hs = new HashSet<>();
boolean b1 = hs.add("a");
boolean b2 = hs.add("a");//當儲存不成功的時候,返回false
System.out.println(b1);
System.out.println(b2);
for(String s : hs) {
System.out.println(s);
}
HashSet儲存自訂對象保證元素唯一性
* A:案例示範
* 儲存自訂對象,並保證元素唯一性。
HashSet<Person> hs = new HashSet<>();
hs.add(new Person("張三", 23));
hs.add(new Person("張三", 23));
hs.add(new Person("李四", 23));
hs.add(new Person("李四", 23));
hs.add(new Person("王五", 23));
hs.add(new Person("趙六", 23));
* 重寫hashCode()和equals()方法
public static void demo1() {
HashSet<String> hs = new HashSet<>();//建立HashSet對象
boolean b1 = hs.add("a");
boolean b2 = hs.add("a");//當向set集合中儲存重複元素的時候返回為false
hs.add("b");
hs.add("c");
hs.add("d");
System.out.println(hs);//HashSet的繼承體系中有重寫toString方法
System.out.println(b1);
System.out.println(b2);
for (String string : hs) {//只要能用迭代器迭代的,就可以使用增強for迴圈遍曆
System.out.println(string);
}
}
java Set ,HashSet