当前位置:网站首页>Pit record_ TreeSet custom sorting results in less data loss

Pit record_ TreeSet custom sorting results in less data loss

2022-06-26 10:34:00 My name is 985

Problem code

Customize Comparable
Set set = new TreeSet( Customize Comparable);
set.addAll(List); //List Originally there were 5 individual , result set Only 4 individual , as a result of List Of compareTo The results returned are the same , Lead to the following item Abandoned .

principle

By tracking TreeSet Source code discovery ,TreeSet Used in TreeMap To store objects , take TreeSet The element as Map Of key, Continue tracking TreeMap Of put Method source code when compared to compareTo The return value is 0 when ,key Value doesn't change ( It's actually an update key Corresponding value,TreeSet Of value It's meaningless ), That is, when there are multiple returns 0 situations TreeSet Only the first element will be placed in the , Give up all the rest , The source code is relatively simple , No post here .
summary : When using TreeSet Sorting time , If realized compareTo Method returns 0 Data loss will occur in the case of .

Solution :

  • Method 1 : Just don't let duplicate sorts appear , If the actual business cannot be avoided, change the sorting method .
  • Method 2 : Use jdk8 Of list.stream().distinct().sort( Sort rule ).collect(Collectors.toList());
    Stream#distinct It's based on toString To remove the weight , Can be rewritten List Of the elements in toString Method . If sort identical , It will not appear, only the first element will be put , The following phenomena are all discarded
原网站

版权声明
本文为[My name is 985]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202170529366072.html