美文网首页
集合框架(TreeSet存储Integer类型的元素并遍历) T

集合框架(TreeSet存储Integer类型的元素并遍历) T

作者: 养码哥 | 来源:发表于2018-04-15 09:39 被阅读0次

核心代码:

 package com.wayboo;

import java.util.TreeSet;

/*
 * TreeSet:能够对元素按照某种规则进行排序。
 * 排序有两种方式
 * A:自然排序
 * B:比较器排序
 * 
 * TreeSet集合的特点:排序和唯一
 * 
 * 通过观察TreeSet的add()方法,我们知道最终要看TreeMap的put()方法。
 */
public class TreeSetDemo {
public static void main(String[] args) {
    // 创建集合对象
    // 自然顺序进行排序
    TreeSet<Integer> ts = new TreeSet<Integer>();

    // 创建元素并添加
    // 20,18,23,22,17,24,19,18,24
    //自动装箱
    ts.add(20);
    ts.add(18);
    ts.add(23);
    ts.add(22);
    ts.add(17);
    ts.add(24);
    ts.add(19);
    ts.add(18);
    ts.add(24);

    // 遍历
    for (Integer i : ts) {
        System.out.println(i);
        }
    }
}

集合框架(TreeSet保证元素排序的源码解析)

   interface Collection {...}

interface Set extends Collection {...}

interface NavigableMap {

}

class TreeMap implements NavigableMap {
 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();
        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;
   }
}

class TreeSet implements Set {
private transient NavigableMap<E,Object> m;

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

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

真正的比较是依赖于元素的compareTo()方法,而这个方法是定义在 Comparable里面的。
所以,你要想重写该方法,就必须是先 Comparable接口。这个接口表示的就是自然排序。

相关文章

网友评论

      本文标题:集合框架(TreeSet存储Integer类型的元素并遍历) T

      本文链接:https://www.haomeiwen.com/subject/mxcdkftx.html