java – CompareTo可能返回0,替代TreeSet / TreeMap

我需要一组有序的对象,目前正在使用TreeSet.我的问题是对象的compareto通常会返回0,这意味着这两个对象的顺序保持不变. TreeMap(认情况下由TreeSet使用)将把它们视为同一个对象,但这不是真的.

我可以使用TreeMap的替代方案吗?

使用案例:我有一组可显示的对象.我想按Y坐标对它们进行排序,以便它们以正确的顺序呈现.当然,两个对象可能具有相同的Y坐标.

解决方法

您要定义一个要比较的条件,但您需要添加额外的条件.

你说:

I have a set of displayable objects. I want to sort them by Y coordinate,so that they are rendered in the correct order. Of course,two objects may well have the same Y coordinate.

那么,如果两个元素具有相同的Y坐标,那么你先放入什么?其他标准是什么?

它可能是创建时间,也可能是x坐标,您只需要定义它:

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;
     }
});

你必须定义什么时候一件东西比其他东西更高/更低/相等/更高.如果其中一个属性与其他属性相同,则可能不应移动它们.如果有其他属性要比较使用它.

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...