TreeMap对象自定义排序时的异常情况

使用treeMap按照对象中的某个属性排序时,传入比较器对对象属性的值进行比较,当不同对象的属性值相同时,此时treeMap的put和get,remove都会出现异常情况;

put

使用treeMap添加对象时,如果对象的属性值相等,会出现key丢失,值覆盖的情况;

示例代码:

public static void main(String[] args) {
    //使用treeMap对student对象的年龄排序
        TreeMap<Student, Integer> treeMap = new TreeMap<>(Comparator.comparing(Student::getAge));
        treeMap.put(new Student("小明", 18), 1);
        treeMap.put(new Student("小红", 20), 2);
        treeMap.put(new Student("小花", 18), 3);
        System.out.println(new Gson().toJson(treeMap));
    }

    public static class Student{
        private String name;
        private Integer age;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Integer getAge() {
            return age;
        }

        public void setAge(Integer age) {
            this.age = age;
        }

        public Student(String name, Integer age) {
            this.name = name;
            this.age = age;
        }

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

实际输出:

{"Student{name='小明', age=18}":3,"Student{name='小红', age=20}":2}

 期望的map中包含三个student对象,实际结果只有两个,其中name=小花的student key丢失,对应的值赋值了小明的student上;

源码:

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判断
        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
                     //比较器返回0,当前值与节点值相等,此时直接在当前节点写入value;
                    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;
    }

treeMap在执行put操作时,如果比较器返回0,循环比较中无法继续向左或向右比较,直接在当前节点t.setValue(value),就会出现当前key丢失,原key的值被覆盖;

要解决这个问题,只需要在传入比较器的时候,当两个属性值相同时,不要返回0,直接返回1/-1;

public static void main(String[] args) {
        TreeMap<Student, Integer> treeMap = new TreeMap<>((o1, o2) -> 
                o1.getAge().compareTo(o2.getAge()) == 0 ? 1 : o1.getAge().compareTo(o2.getAge()));
        treeMap.put(new Student("小明", 18), 1);
        treeMap.put(new Student("小红", 20), 2);
        treeMap.put(new Student("小花", 18), 3);
        System.out.println(new Gson().toJson(treeMap));
    }

remove

解决不同对象属性值相同的put问题后,此时想删除treeMap中的key时,会发现remove失败;

实例代码:

public static void main(String[] args) {
    TreeMap<Student, Integer> treeMap = new TreeMap<>((o1, o2) ->
                                                      o1.getAge().compareTo(o2.getAge()) == 0 ? 1 : o1.getAge().compareTo(o2.getAge()));
    Student ming = new Student("小明", 18);
    treeMap.put(ming, 1);
    Student hong = new Student("小红", 20);
    treeMap.put(hong, 2);
    Student hua = new Student("小花", 18);
    treeMap.put(hua, 3);
    treeMap.remove(ming);
    System.out.println(treeMap.get(ming));
    System.out.println(new Gson().toJson(treeMap));
}

期望结果name=小明的key被移除,剩余两个对象;实际输出:

null
{
  "Student{name=\"小明\", age=18}":1,
  "Student{name=\"小花\", age=18}":3,
  "Student{name=\"小红\", age=20}":2
}

 

使用treeMap.get(key)时,返回值为null,remove也没有成功;

看一下treeMap的put过程:

1.先添加 小明:18,根节点;

2.添加 小红:20;比较器比较20>18,加在根节点右边;

3.添加 小花:18;与根节点比较,值相等,比较器返回1,向右与小红比较,18<20,加在小红左边子节点;

4.红黑树变形;

当执行treeMap.get(ming)时,先与根节点小花比较,虽然值都是18,但是我们比较器属性相同返回1,继续向右与小红比较,比小红小,从小红的子节点中向左比较,未找到子节点,返回为null;

源码:

final Entry<K,V> getEntryUsingComparator(Object key) {
@SuppressWarnings("unchecked")
K k = (K) key;
Comparator<? super K> cpr = comparator;
if (cpr != null) {
    Entry<K,V> p = root;
    while (p != null) {
        int cmp = cpr.compare(k, p.key);
        if (cmp < 0)
            p = p.left;
        else if (cmp > 0)
            p = p.right;
        else
            //因为传入的比较返回恒不为0,所以无法取到值;
            return p;
    }
}
return null;
}

使用treeMap.get(key)获取值时,会通过传入的比较器进行比较查找,只有当 cpr.compare(k, p.key)返回0时,才会返回查找的节点,上述操作中我们将比较器中等于0的场景恒返回为1,所以在获取值时会一直向右比较,直到查找不到,返回null;

避免方案

当我们要使用TreeMap对对象进行排序时,不可避免会出现不同对象的属性值相同情况,如果比较器正常返回,会导致插入覆盖,如果处理后不返回0,又会导致获取不到值,怎么处理这种场景呢?

其实我们可以构建多个排序字段,来确保两个不同对象在排序规则上能够正常返回大小,代码如下:

public static void main(String[] args) {
        //使用treeMap对student对象的年龄排序
        TreeMap<Student, Integer> treeMap = new TreeMap<>((o1, o2) -> {
            //当年龄相同时,按照学生姓名自然排序
            if (o1.getAge().compareTo(o2.getAge()) == 0) {
                return o1.getName().compareTo(o2.getName());
            } else {
                return o1.getAge().compareTo(o2.getAge());
            }
        });
        Student ming = new Student("小明", 18);
        treeMap.put(ming, 1);
        Student hong = new Student("小红", 20);
        treeMap.put(hong, 2);
        Student hua = new Student("小花", 18);
        treeMap.put(hua, 3);
        System.out.println(GsonUtil.toJson(treeMap));
        System.out.println(treeMap.get(hua));
    }

总结

TreeMap通过比较器中比较的属性作为插入和获取值的依据,当key为对象时,即使为不同的对象,当比较的属性值相同时,还是会发生覆盖问题;获取时也是依据比较器从根节点逐一比较,找到值相同的节点返回;避免这种情况,要让比较器正确返回两个对象的大小;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值