Java 集合-Set接口和三個子類實現


2017-10-31 19:20:45

  • Set

一個不包含重復元素的 collection。無序且唯一。

    1. HashSet
    2. LinkedHashSet
    3. TreeSet

HashSet是使用哈希表(hash table)實現的,其中的元素是無序的。HashSet的addremovecontains方法 的時間復雜度為常量O(1)。

TreeSet使用樹形結構(算法書中的紅黑樹red-black tree)實現的。TreeSet中的元素是可排序的,但addremovecontains方法的時間復雜度為O(log(n))。TreeSet還提供了first()、last()、headSet()、tailSet()等方法來操作排序后的集合。

LinkedHashSet介於HashSet和TreeSet之間。它基於一個由鏈表實現的哈希表,保留了元素插入順序。LinkedHashSet中基本方法的時間復雜度為O(1)。

~ 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()方法,使用idea的alt+insert可以自動生成。

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操作符,這個操作符和== ,>=是同種性質的,只是是用英文描述的,是二元操作符,用來判斷左邊的是否為這個特定類或者是它的子類的一個實例。

 

~ LinkedHashSet

具有可預知迭代順序的 Set 接口的哈希表和鏈接列表實現。此實現與 HashSet 的不同之外在於,后者維護着一個運行於所有條目的雙重鏈接列表。此鏈接列表定義了迭代順序,即按照將元素插入到 set 中的順序(插入順序)進行迭代。注意,插入順序 受在 set 中重新插入的 元素的影響。

哈希表保證元素的唯一性,鏈表保證元素有序,也就是存入順序和取出順序相同。

 

~ TreeSet

基於 TreeMapNavigableSet 實現。使用元素的自然順序對元素進行排序,或者根據創建 set 時提供的 Comparator 進行排序,具體取決於使用的構造方法。

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

有兩種排序方式:A-自然排序,也是默認排序(實現Comparable),B-比較器排序。取決於構造方法。

*構造方法

*常用方法

        // 會自動排序
        TreeSet<Integer> treeSet = new TreeSet<>();

        treeSet.add(12);
        treeSet.add(13);
        treeSet.add(2);
        treeSet.add(4);

        for(int i:treeSet) System.out.println(i);

TreeSet的唯一性解釋,源碼剖析:唯一性根據比較的返回值是否為0,如果為零,則相等;排序的方式有兩種,自然排序和比較器排序。

//TreeSet類
class TreeSet implements Set{
  private static final Object PRESENT = new Object();
  private transient NavigableMap<E,Object> m;

  TreeSet(NavigableMap<E,Object> m) {
        this.m = m;
    }

  public TreeSet() {
        this(new TreeMap<>());
    }

  public boolean add(E e) {
        return m.put(e, PRESENT)==null;
    }
}

//TreeMap類
class TreeMap implements Map{

//紅黑樹實現 public V put(K key, V value) { Entry<K,V> t = root;
     //建立根節點 if (t == null) { compare(key, key); // type (and possibly null) check root = new Entry<>(key, value, null); size = 1; modCount++; return null; } int cmp; Entry<K,V> parent; // split comparator and comparable paths Comparator<? super K> cpr = comparator; if (cpr != null) { do { parent = t; cmp = cpr.compare(key, t.key); if (cmp < 0) t = t.left; else if (cmp > 0) t = t.right; else return t.setValue(value); } while (t != null); } else { if (key == null) throw new NullPointerException(); @SuppressWarnings("unchecked") Comparable<? super K> k = (Comparable<? super K>) key; do { parent = t; cmp = k.compareTo(t.key); if (cmp < 0) t = t.left; else if (cmp > 0) t = t.right; else return t.setValue(value); } while (t != null); } Entry<K,V> e = new Entry<>(key, value, parent); if (cmp < 0) parent.left = e; else parent.right = e; fixAfterInsertion(e); size++; modCount++; return null; } }

對象中的實例,自然排序:具體類實現Comparable接口,重寫Comparable方法。構造方法為默認構造

public class Student implements Comparable<Student>{
    private String name;
    private Integer age;

    Student(String name,int age)
    {
        this.name=name;
        this.age=age;
    }

//    @Override
//    public int hashCode() {
//        return 0;
//    }
//
//    @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);
//    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Student student = (Student) o;

        if (name != null ? !name.equals(student.name) : student.name != null) return false;
        return age != null ? age.equals(student.age) : student.age == null;
    }

    @Override
    public int hashCode() {
        int result = name != null ? name.hashCode() : 0;
        result = 31 * result + (age != null ? age.hashCode() : 0);
        return result;
    }

    @Override
    // 從小到大
    public int compareTo(Student o) {
        int num = this.age-o.age;
        return num==0?this.name.compareTo(o.name):num;
    }
}

對象中的實例,比較器排序:自定義比較器,實現Comparator接口。構造方法為帶比較器的構造

class MyComparator implements Comparator<Student>{

    @Override
    public int compare(Student o1, Student o2) {
        int num = o1.age-o2.age;
        return num==0?o1.name.compareTo(o2.name):num;
    }
}

當然也可以使用匿名內部類來實現。

TreeSet<Student> treeset = new Treeset<>(new Comparator<Student>(){
  public int compare(Student o1, Student o2) { int num = o1.age-o2.age; return num==0?o1.name.compareTo(o2.name):num; }
})

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM