Java 集合-Set介面及其子類

來源:互聯網
上載者:User

標籤:his   一個   常用   tin   http   技術分享   解決   重寫   返回   

2017-10-31 19:20:45

Set:無序且唯一

實現子類:HashSet,

  • HashSet

此類實現 Set 介面,由雜湊表(實際上是一個 HashMap 執行個體)支援。它不保證 set 的迭代順序;特別是它不保證該順序恒久不變。此類允許使用 null 元素。

注意,此實現不是同步的。如果多個線程同時訪問一個雜湊 set,而其中至少一個線程修改了該 set,那麼它必須 保持外部同步。

HashSet底層資料結構是雜湊表(HashMap),雜湊表依賴於雜湊值儲存,添加功能底層依賴兩個方法:int hashCode(),boolean equals(Object obj)。

*構造方法

*常用方法

HashSet唯一性的解釋:

源碼剖析:添加功能底層依賴兩個方法:int hashCode(),boolean equals(Object obj)

//HashSet類class HashSet implements Set{  private static final Object PRESENT = new Object();  private transient HashMap<E,Object> map;  // 構造方法,返回了一個HashMap  public HashSet() {        map = new HashMap<>();    }  //add方法  public boolean add(E e) {        return map.put(e, PRESENT)==null;    }}//HashMap類class HashMap implements Map{  public V put(K key, V value) {        return putVal(hash(key), key, value, false, true);    }  final V putVal(int hash, K key, V value, boolean onlyIfAbsent,                   boolean evict) {        Node<K,V>[] tab; Node<K,V> p; int n, i;        if ((tab = table) == null || (n = tab.length) == 0)            n = (tab = resize()).length;        if ((p = tab[i = (n - 1) & hash]) == null)            tab[i] = newNode(hash, key, value, null);        else {            Node<K,V> e; K k;            if (p.hash == hash &&                ((k = p.key) == key || (key != null && key.equals(k))))                e = p;            else if (p instanceof TreeNode)                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);            else {                for (int binCount = 0; ; ++binCount) {                    if ((e = p.next) == null) {                        p.next = newNode(hash, key, value, null);                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st                            treeifyBin(tab, hash);                        break;                    }                    if (e.hash == hash &&                        ((k = e.key) == key || (key != null && key.equals(k))))                        break;                    p = e;                }            }            if (e != null) { // existing mapping for key                V oldValue = e.value;                if (!onlyIfAbsent || oldValue == null)                    e.value = value;                afterNodeAccess(e);                return oldValue;            }        }        ++modCount;        if (++size > threshold)            resize();        afterNodeInsertion(evict);        return null;    }}

一個執行個體問題,在這種添加自訂對象的時候,兩個類的屬性值相等,但是依然會被判定為不同的元素,因為沒有重寫hashCode(),所以預設調用的是Object類的hashCode(),而不同類的hashCode一般是不同的。

        HashSet<Student> hashSet = new HashSet<>();        Student s1 = new Student("劉亦菲", 22);        Student s2 = new Student("章子怡", 25);        Student s3 = new Student("劉亦菲", 22);        hashSet.add(s1);        hashSet.add(s2);        hashSet.add(s3);        System.out.println(hashSet);

解決方案就是自己重寫hashCode() 和 equals()方法:

public class Student {    private String name;    private Integer age;    Student(String name,int age)    {        this.name=name;        this.age=age;    }    @Override    public int hashCode() {        // return 0;
     return this.name.hashCode()+this.age*11; } @Override public boolean equals(Object obj) { if(this == obj) return true; if(!(obj instanceof Student)) return false; Student s = (Student) obj; return this.name.equals(s.name) && this.age.equals(s.age); }}

這裡用到了instanceof操作符,這個操作符和== ,>=是同種性質的,只是是用英文描述的,是二元操作符,用來判斷左邊的是否為這個特定類或者是它的子類的一個執行個體。

 

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.