zoukankan      html  css  js  c++  java
  • TreeMap——实现comparable接口并重写CompareTo方法

    public class TreeMapTest {
    
        public static void main(String[] args) {
            Map<Student,Integer> students = new TreeMap<>();
            students.put(new Student("11"),1);
            students.put(new Student("11"),1);
            System.out.println(students.size());
        }
    }

    输出结果为2

    因为

     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方法,看结果来看新存入的值放在左侧(cmp<0),还是右侧(cmp>0),还是现在的value值把原来的value值覆盖(cmp=0)

    需要在Student类中重写compareTo方法

        @Override
        public int compareTo(Student o) {
            return 0;
        }

    按照你自己的要求重写compareTo方法就行了~

  • 相关阅读:
    定时器
    Eclipse 启动时闪退问题解决方案
    VMware下安装centos6.7的步骤
    bin/mysqld: error while loading shared libraries: libnuma.so.1: 安装mysql
    CentOS系统bash: groupadd: command not found问题
    MyBatis Sql语句中的转义字符
    Postgresql 正则表达式
    JS生成GUID方法
    jqGrid 事件
    jqgrid 事件说明
  • 原文地址:https://www.cnblogs.com/lyxcode/p/9470612.html
Copyright © 2011-2022 走看看