java中的set集合

來源:互聯網
上載者:User

標籤:set

import java.util.HashSet;import java.util.Iterator;import java.util.Set;public class SetTest01 {/*Set集合:HashSet1.HashSet底層實際上是一個HashMap,HashMap底層採用了雜湊表資料結構。2.雜湊表又叫做散列表,雜湊表底層是一個數組,這個數組中每一個元素是一個單向鏈表。每個單向鏈表都有一個獨一無二的hash值,代表數組的下標。在某個單向鏈表中的每一個節點上的hash值是相等的。hash值實際上是key調用hashCode方法,在通過"hash function"轉換成的值。3.如何向雜湊表中添加元素:先調用被儲存的key的hashCode方法,經過某個演算法得出hash值,如果在這個雜湊表中不存在這個 hash值,則直接加入元素。如果該hash值已經存在,繼續調用key之間的equals方法,如果equals方法返回false,則將該元素添加。如果equals方法返回true,則放棄添加該元素。4.HashSet其實是HashMap中的key部分。HashSet有什麼特點,HashMap中的key 應該具有相同的特點。5.HashMap和HashSet初始化容量都是 16,預設載入因子是0.75*///入口public static void main(String[] args){//建立Set集合Set s = new HashSet();//無序不可重複s.add(1);s.add(1);s.add(100);s.add(85);s.add(88);//遍曆Iterator it = s.iterator();while(it.hasNext()){System.out.println(it.next());}//結論:儲存在HashSet集合或者HashMap集合key部分的元素,需要同時重寫hashCode+equals                Set es = new HashSet();Employee e1 = new Employee("1000","JACK");Employee e2 = new Employee("1000","JACK");Employee e3 = new Employee("1000","SCOTT");Employee e4 = new Employee("2001","SUN");Employee e5 = new Employee("3000","JIM");Employee e6 = new Employee("3001","COOK");System.out.println(e1.hashCode());System.out.println(e2.hashCode());//添加元素es.add(e1);es.add(e2);es.add(e3);es.add(e4);es.add(e5);es.add(e6);//查看集合元素個數System.out.println(es.size()); //}}public class Employee {private String id;//idprivate String name;//namepublic String getNo() {return id;}public void setNo(String id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}//構造方法public Employee(String id, String name) {super();this.id = id;this.name = name;}public Employee(){}//重寫了hashcode方法。public int hashCode() {return id.hashCode();}//重寫了equals方法。public boolean equals(Object obj) {if(obj==this){return true;}else{if(obj instanceof Employee){Employee e = (Employee)obj;if(e.id.equals(this.id)&&e.name.equals(this.name)){return true;}}}return false;}


本文出自 “gaogaozi” 部落格,請務必保留此出處http://hangtiangazi.blog.51cto.com/8584103/1669561

java中的set集合

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.