栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java集合框架Part13

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java集合框架Part13

目录
  • TreeSet基本介绍
  • TreeSet基本用法
    • 使用无参构造器创建TreeSet对象
    • 使用有参构造器创建TreeSet对象
  • TreeSet源码剖析

TreeSet基本介绍

TreeSet基本用法 使用无参构造器创建TreeSet对象
public class TreeSet_ {
    public static void main(String[] args) {
        //输出的结果和数据插入的顺序不一致
        TreeSet treeSet = new TreeSet();
        treeSet.add("jack");
        treeSet.add("roy");
        treeSet.add("alisa");
        treeSet.add("cecil");
        System.out.println(treeSet);
    }
}
[alisa, cecil, jack, roy]
使用有参构造器创建TreeSet对象
public class TreeSetSortable {
    public static void main(String[] args) {
        //按字母升序排列
        TreeSet treeSet = new TreeSet(new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                return ((String) o1).compareTo(((String) o2));
            }
        });
        treeSet.add("jack");
        treeSet.add("roy");
        treeSet.add("alisa");
        treeSet.add("cecil");
        System.out.println(treeSet);
    }
}
[alisa, cecil, jack, roy]
TreeSet源码剖析
public TreeSet(Comparator comparator) {
    this(new TreeMap<>(comparator));
}
public boolean add(E e) {
    return m.put(e, PRESENT)==null;
}
public V put(K key, V value) {
    Entry t = root;
    //插入第一个数据,t为null,进入这个if条件
    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 parent;
    // split comparator and comparable paths
    //comparator会动态绑定到我们写的匿名内部类对象
    Comparator cpr = comparator;
    if (cpr != null) {
        do {
            parent = t;
            //比较
            cmp = cpr.compare(key, t.key);
            if (cmp < 0)
                //t=t.left,如果左侧还有节点,那么while循环会继续比较
                t = t.left;
            else if (cmp > 0)
                //t=t.right,如果右侧还有节点,那么while循环会继续比较
                t = t.right;
            else
                return t.setValue(value);
        } while (t != null);
    }
    else {
        if (key == null)
            throw new NullPointerException();
        @SuppressWarnings("unchecked")
        Comparable k = (Comparable) 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 e = new Entry<>(key, value, parent);
    if (cmp < 0)
        parent.left = e;
    else
        parent.right = e;
    fixAfterInsertion(e);
    size++;
    modCount++;
    return null;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/835885.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号