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

  • 相关阅读:
    操作系统六文件管理
    Educational Codeforces Round 38 (Rated for Div. 2) ABCD
    51nod 1100 斜率最大
    51nod 最小方差
    51nod 1065 最小正子段和
    P1280 尼克的任务
    牛客小白月赛2
    Codeforces Round #210 (Div. 1) B 二分+dp
    江西财经大学第一届程序设计竞赛
    51nod 1596 搬货物
  • 原文地址:https://www.cnblogs.com/lyxcode/p/9467257.html
Copyright © 2011-2022 走看看