如何在列表中自定义/排序对象

Kri*_*nya 6 java sorting

我有一个对象列表,我想按特定顺序排序/排序.

我有一个Promotion对象列表.每个促销活动都有描述.所有促销中的两个将描述设置为"高级"和"普通"

我想对列表进行排序/排序,使得带有描述"premium"的促销应始终位于列表的末尾,并且具有描述"普通"的促销始终位于list.size - 1位置.以下示例

[{description = ...},{description = ...},..... {description = ordinary},{description = premium}]

我尝试使用Collections.sort通过传递下面的自定义Comparator对对象进行排序

public int compare(Promotion p1, Promotion p2) {
        if(p1.getDescription().equals("ordinary")) {
    return -size-1; // size is the size of the list passed as a constructor argument to the Comparator.
    }
if(p1.getDescription().equals("premium")) {
    return -size;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)

我尝试使用上面的代码,测试时没有得到所需的输出.

我后来在每个if条件中添加了另一个检查来检查p2对象中的描述,如下所示

p1.getDescription().equals("premium") || p2.getDescription().equals("premium")
Run Code Online (Sandbox Code Playgroud)

我在这做错了什么?或者我以错误的方式使用Collections.sort?任何人都可以建议/帮助我吗?

小智 6

比较方法比较需要两个元件,并且如果返回一个负值X <Y,0,如果x等于ý或者如果正值X> Y.

在这种情况下,您可以将类放在一个按优先级排序的数组中,如下所示:

String classes[] = new String[]{"premimum", "ordinary", "less than ordinary"};
Run Code Online (Sandbox Code Playgroud)

那么你可以比较像这样的元素的索引:

public int compare(Promotion p1, Promotion p2) {
Integer index1 = getIndexInsideClasses(p1.getDescription);
Integer index2 = getIndexInsideClasses(p2.getDescription);
       return index1.compareTo(index2);
   }
Run Code Online (Sandbox Code Playgroud)

  • 我会使用List代替`classes`的数组,并利用`indexOf`如果搜索的描述不在List上则返回-1.所以List只需要包含"普通"和"溢价"`.(或者只是`getIndexInsideClasses`里面的一个开关) (2认同)
  • 比较器不一定返回"-1"或"1".定义是"消极的"或"积极的".`-1`和`-5`一样合法(并且具有完全相同的含义). (2认同)