【问题标题】:Sort the list of custom object w.r.t. a data member对自定义对象列表进行排序 w.r.t.数据成员
【发布时间】:2014-02-20 17:33:44
【问题描述】:

我有一个应用程序列表,其中每个实体都代表一个自定义对象。

List<String> Applications = new ArrayList<String>();

我的应用程序类是这样的:

public Class Application
{
    private String ApplicationName;
    private int Priority
}

我需要对应用程序进行排序 w.r.t.优先。请注意,Priority 只能包含三个意志值,即 1、2 和 3 分别代表 High、Medium 和 Low。

我已经实现了 Comparator 来像这样对列表进行排序:

Collections.sort(this.Applications, new Comparator<Application>()
{
    @Override
    public int compare(Application App1, Application App2)
    {
        return App1.Priority.compareTo(App2.Priority);
    }
});

但是编译器给了我这个错误:

Cannot invoke compareTo(int) on the primitive type int

【问题讨论】:

  • 主要问题是int 是原始类型,而不是类,并且有NO 方法可以从原始类型调用。 LouisWasserman's answer 解释了如何解决这个问题。
  • 请注意,Java 约定是变量和方法名称应以小写字母开头:app1.priority。遵循此约定将使您的代码更容易被其他人理解。

标签: java android sorting


【解决方案1】:

如果您使用的是 Java 7,请替换

return IA1.Priority.compareTo(IA2.Priority);

return Integer.compare(IA1.Priority, IA2.Priority);

...否则,您必须将其替换为

if (IA1.Priority < IA2.Priority) {
  return -1;
} else if (IA1.Priority == IA2.Priority) {
  return 0;
} else {
  return 1;
}

【讨论】:

  • 或者干脆return IA2.Priority - IA1.Priority;
  • @NeplatnyUdaj 可能会导致溢出。
  • luiggi-mendoza:没错,但我认为应用程序的优先级不会是一个很大的负数。我同意这不是一个很好的建议:)
  • @louis:我正在为 Android 开发。因此,您的第一个替换给了我这个错误:Call requires API level 19 (current min is 8)
  • @Faheem 如果优先级确实限制为值 1、2 和 3,则将其设为枚举可能是有意义的。类型安全,您将免费获得compareTo
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-13
  • 1970-01-01
  • 2013-05-06
  • 2021-07-11
相关资源
最近更新 更多