java Set ,HashSet

來源:互聯網
上載者:User

標籤:使用   元素   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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.