zoukankan      html  css  js  c++  java
  • TreeSet——实现Comparable接口并重写CompareTo()方法

    TreeSet是以自然顺序存的数据,例如

    Set<Student> students=new TreeSet();
            students.add(new Student("111"));
            students.add(new Student("333"));
            students.add(new Student("222"));
            
            for (Student student : students) {
                System.out.println(student.getId());
            }

    输出结果为111  222  333

    而且这时候的Student必须继承Comparable接口,重写抽象方法CompareTo方法

    public class Student implements Comparable<Student> {
    
        private String id;
    
        
        public Student(String id) {
            this.id = id;
        }
    
    
    
    
        @Override
        public int compareTo(Student o) {
            return 1;
        }
    
    }

    出现这样的效果是因为存储的时候的代码是这样的

    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;
        }

    看红色的代码,存储的时候执行compareTo方法,这个时候就会判断你存的值得大小顺序,然后判断你该存储的顺序,就是自然顺序了。。

  • 相关阅读:
    两类斯特林数的整理
    SXOI2019游记
    3.13校内测试
    Python Flask 实现移动端应用接口(API)
    CentOS下实现Flask + Virtualenv + uWSGI + Nginx部署
    iOS组件化开发入门 —— 提交自己的私有库
    Runtime ----- 带你上道
    iOS核心动画以及UIView动画的介绍
    GCD中各种队列和任务执行方式的组合
    iOS消息转发机制和使用
  • 原文地址:https://www.cnblogs.com/lyxcode/p/9467257.html
Copyright © 2011-2022 走看看