相关疑难解决方法(0)

按属性排序自定义对象的ArrayList

我读到了使用Comparator对ArrayLists进行排序,但在所有人们使用的例子中compareTo,根据一些研究,这是一个字符串的方法.

我想通过它们的一个属性对自定义对象的ArrayList进行排序:Date对象(getStartDay()).通常我会比较它们item1.getStartDate().before(item2.getStartDate())所以我想知道我是否可以这样写:

public class CustomComparator {
    public boolean compare(Object object1, Object object2) {
        return object1.getStartDate().before(object2.getStartDate());
    }
}

public class RandomName {
    ...
    Collections.sort(Database.arrayList, new CustomComparator);
    ...
}
Run Code Online (Sandbox Code Playgroud)

java sorting date comparator

1093
推荐指数
18
解决办法
104万
查看次数

什么时候课程应该是可比较的和/或比较者?

我见过同时实现ComparableComparator的类.这是什么意思?为什么我会使用一个而不是另一个?

java comparable comparator

134
推荐指数
8
解决办法
22万
查看次数

Java Integer compareTo() - 为什么使用比较与减法?

我发现方法的java.lang.Integer实现compareTo如下:

public int compareTo(Integer anotherInteger) {
    int thisVal = this.value;
    int anotherVal = anotherInteger.value;
    return (thisVal<anotherVal ? -1 : (thisVal==anotherVal ? 0 : 1));
}
Run Code Online (Sandbox Code Playgroud)

问题是为什么使用比较而不是减法:

return thisVal - anotherVal;
Run Code Online (Sandbox Code Playgroud)

java optimization comparison integer overflow

78
推荐指数
3
解决办法
1万
查看次数

如何按属性对对象的arylylist进行排序?

比方说你有一个ArraylistHockeyPlayer对象.

如果他们都有一个变量int goalsScored你怎么能排序.你怎么能按目标排序呢?

java sorting collections

37
推荐指数
4
解决办法
9万
查看次数