Java – CompareTo may return 0 instead of TreeSet / treemap

I need an ordered set of objects and am currently using TreeSet My problem is that CompareTo of objects usually returns 0, which means that the order of the two objects remains the same Treemap (used by TreeSet by default) will treat them as the same object, but this is not true

Can I use an alternative to treemap?

Use case: I have a set of objects to display I want to sort them by Y coordinate so that they appear in the correct order Of course, two objects may have the same y coordinate

Solution

You want to define a condition to compare, but you need to add additional conditions

You say?

So, if two elements have the same y coordinate, what do you put in first? What are the other criteria?

It may be the creation time or the X coordinate. You only need to define it:

Map<String,Thing> map = new TreeMap<String,Thing>(new Comparator<Thing>(){
     public int compare( Thing one,Thing two ) {
         int result = one.y - two.y;
         if( result == 0 ) { // same y coordinate use another criteria
             result = one.x - two.x;
             if( result == 0 ) { //still the same? Try another criteria ( maybe creation time
                 return one.creationTime - two.creationTime
             }
          }
          return result;
     }
});

You must define when one thing is higher / lower / equal / higher than others If one of the attributes is the same as the others, they may not be moved If there are other attributes to compare, use it

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>