关于对TreeSet集合中的元素可以按照元素的大小顺序自动排序的理解

关于对TreeSet集合中的元素可以按照元素的大小顺序自动排序的理解

  1. 调用TreeSet的add()方法向TreeSet集合中添加元素,等同于向TreeMap集合key部分添加元素
    TreeSet集合底层add方法源代码
 public boolean add(E e) {
    return m.put(e, PRESENT)==null;
}

2.调用TreeSet的add()方法向TreeSet集合中添加元素,等同于向TreeMap集合key部分添加元素,因此我们查看TreeMap底层的put方法可知
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);
                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;
    }

3.可以看出TreeMap集合底层数据结构是一个平衡二叉树,当调用put()方法添加元素时,他会判断Comparator<? super K> cpr = comparator中的comparator是不是为null,如果不为null,他会进行cmp = cpr.compare(key, t.key);方法进行比较然后根据平衡二叉树的特性进行排序,如果comparator为null,他会进行类型转换Comparable<? super K> k = (Comparable<? super K>) key;然后调用cmp = k.compareTo(t.key);方法进行比较然后根据平衡二叉树的特性进行排序。
4.因此我们要对自定义类型进行TreeSet排序有二种实现方式
第一种:放在集合中的元素实现java.lang.Comparable接口
测试代码

package com.tedu.CollectionPackage;

import java.util.TreeSet;

public class TreeSetTest1 {
    public static void main(String[] args) {
        TreeSet<User> treeSet = new TreeSet<>();
        treeSet.add(new User(1,"张三"));
        treeSet.add(new User(7,"刘琦"));
        treeSet.add(new User(3,"直至"));
        treeSet.add(new User(6,"赵亮"));
        treeSet.add(new User(5,"王麻子"));
        treeSet.add(new User(2,"李四"));
        for (User user : treeSet){
            System.out.println(user);
        }
    }
}
class User implements  Comparable<User>{
    Integer id;
    String name;

    public User(Integer id, String name) {
        this.id = id;
        this.name = name;
    }

    public User() {
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
    //自定义排序规则
    @Override
    public int compareTo(User o) {
        //因为底层采用了二叉树的数据结构
        return this.id - o.id;
    }
}

注意点:采用第一种方式,在对自定义类型进行TreeSet排序时,我们一定要去实现Comparable接口,重写compareTo方法,自定义比较规则,不然会出现类型转化异常
第二种:在构建TreeSet或者TreeMap集合的时候给他传一个比较器对象
测试代码

package com.tedu.CollectionPackage;

import java.util.Comparator;
import java.util.TreeSet;

public class TreeSetTest2 {
    public static void main(String[] args) {
        TreeSet<Customer> treeSet = new TreeSet<>(new Comparator<Customer>() {
            @Override
            public int compare(Customer o1, Customer o2) {
                return o1.getId() - o2.getId();
            }
        });
        Customer customer1 = new Customer(1, "张三");
        Customer customer2 = new Customer(4, "李四");
        Customer customer3 = new Customer(3, "王麻子");
        Customer customer4 = new Customer(2, "赵亮");
        treeSet.add(customer1);
        treeSet.add(customer2);
        treeSet.add(customer3);
        treeSet.add(customer4);
        for(Customer customer : treeSet){
            System.out.println(customer);
        }
    }
}
class Customer{
    private int id;
    private String name;

    @Override
    public String toString() {
        return "Customer{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }

    public Customer(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public Customer() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值