1. 程式人生 > >Java 集合-Set接口及其子類

Java 集合-Set接口及其子類

允許 ret ins ict amp println out ++ ||

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接口及其子類