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方法,这个时候就会判断你存的值得大小顺序,然后判断你该存储的顺序,就是自然顺序了。。

  • 相关阅读:
    2018年第九届蓝桥杯国赛总结(JavaB组)
    yzm10的小简介
    论文学习笔记
    Tied Block Convolution:一种共享filter的卷积形态
    AI艺术鉴赏挑战赛
    论文学习笔记
    (转)论文学习笔记
    论文学习笔记
    2020 计蒜之道 预赛 第三场 石子游戏(简单)(暴力DP)
    第六周:生成式对抗网络
  • 原文地址:https://www.cnblogs.com/lyxcode/p/9467257.html
Copyright © 2011-2022 走看看