java 基礎 --Collection(Set)

來源:互聯網
上載者:User

標籤:條件   tor   equals   java   put   present   exce   static   依賴   

注意:

如果hashSet儲存自訂對象,一定要重寫hashCode()&&equals()

如果TreeSet儲存自訂對象,讓元素所屬的類實現自然排序介面Comparable,並重寫CompareTo()/讓集合的構造方法接收一個比較子介面的子類對象Comparator

結構:
Set:
|--HashSet(底層結構是Hash表(Hash表:元素是鏈表的數組,Hash表依賴於Hash值儲存))
|--LinkedHashSet(底層機構是鏈表和Hash表)
|--TreeSet(底層是二叉樹結構(紅/黑樹狀結構是一種自平衡的二叉樹))

詳解:
Set
無序(儲存順序和取出順序不一致),唯一(雖然set集合的元素無序,但是作為集合來說肯定有它的儲存順序,而你的儲存順序和它的順序一致,這代表不了有序。)
|-- HashSet

HashSet底層依賴的是hashCode()和equals()
所以儲存自訂對象時,對象需要重寫hashCode()和equals()來保證唯一性(自動重寫即可)

HashSet 底層源碼:
①HashSet<String> set = new HashSet<String>();
   public HashSet() {
        map = new HashMap<>();
    }
②set.add("atomic");
private static final Object PRESENT = new Object();
public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }
源碼結論:HashSet是一個HashMap,它的值儲存在HashMap的Key中,因此hashSet資料是唯一的

if (e.hash == hash && //先看hashCode(),如果hash值相同,不添加元素
    ((k = e.key) == key || (key != null && key.equals(k)))){break;} //如果元素值/地址值相同(元素重複),也不添加元素
p = e;//以上三種情況外才添加元素

TreeSet:自然排序,唯一(TreeSet底層就是treeMap)
API: A NavigableSet implementation based on a TreeMap
①如果是基本類型,會自動進行排序,去重
②如果是自訂類型,需要重寫...

真正的比較依賴於元素的CompareTo()方法,而這個方法是定義在Comparable裡面的,
所以要想重寫該方法,就必須先實現COmparable介面,這個介面表示的就是自然排序
底層是二叉樹結構(紅/黑樹狀結構是一種自平衡的二叉樹)。
二叉樹三種遍曆:
中序遍曆:先左子樹,後根節點,再右子樹
前序走訪:先根節點,後左子樹,再右子樹
後序遍曆:先左子樹,後右子樹,再根節點

源碼:①TreeSet<String> set = new TreeSet<String>();
   ②set.add("d");

public boolean add(E e) {
        return m.put(e, PRESENT)==null;
    }
private transient NavigableMap<E,Object> m;
API: A NavigableSet implementation based on a TreeMap

TreeMap的put();
  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);//key-t.key
                if (cmp < 0)                  // key小放左邊
                    t = t.left;
                else if (cmp > 0)             // key大放右邊
                    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;
    }


總結:TreeSet集合保證元素排序和唯一性的原理
唯一性:根據比較的傳回值是否為0來決定的
排序:
A:自然排序(元素具備比較性)
讓元素所屬的類實現自然排序介面Comparable
B:比較子排序(集合具備比較性)
讓集合的構造方法接收一個比較子介面的子類對象Comparator
舉例:A:
// 方式1:
TreeSet<Student> ts1 = new TreeSet<Student>();
// 如果一個類想要進行自然排序,就必須實現自然排順序介面
public class Student implements Comparable<Student>{
  private String name;
  private int age;
  @Override
               public int compareTo(Student o) {
                 // 按年齡,主要條件
                  int num = this.age - o.age;
                  //  次要條件,年齡相同時好要看名字是否相同
                  //  如果名字和年齡都相同,才是一個元素
                  int num2 = num == 0?this.name.compareTo(o.name):num;
                  return num2;

/* 按名字排序
               @Override
               public int compareTo(Student o) {
  
                  //  按姓名,主要條件
                  int num = this.name.length() - o.name.length();
                  //  姓名長度相同不代表內容相同
                  int num2 = num == 0?this.name.compareTo(o.name):num;
                  //  姓名長度和內容相同,不代表年齡相同
                  int num3 = num2 == 0?this.age-o.age:num2;
                  return num3;
                  }
*/
          }

B:
//方式2
TreeSet<Student> ts2 = new TreeSet<Student>(new MyComparator());
// 實現Comparator()介面
             public class MyComparator implements Comparator<Student> {
              @Override
                public int compare(Student o1, Student o2) {
                    // 按姓名,主要條件
                    int num = o1.getName().length() - o2.getName().length();
                    // 姓名長度相同不代表內容相同
                    int num2 = num == 0 ? o1.getName().compareTo(o2.getName()) : num;
                    // 姓名長度和內容相同,不代表年齡相同
                    int num3 = num2 == 0 ? o1.getAge() - o2.getAge() : num2;
                    return num3;
                }
            }
//方式3(匿名類方式)
            TreeSet<Student> ts3 = new TreeSet<Student>(new Comparator<Student>() {
                @Override
                public int compare(Student o1, Student o2) {
                    // 按姓名,主要條件
                    int num = o1.getName().length() - o2.getName().length();
                    // 姓名長度相同不代表內容相同
                    int num2 = num == 0 ? o1.getName().compareTo(o2.getName()) : num;
                    // 姓名長度和內容相同,不代表年齡相同
                    int num3 = num2 == 0 ? o1.getAge() - o2.getAge() : num2;
                    return num3;
                }
            });

 

java 基礎 --Collection(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.