我读到了使用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) 我见过同时实现Comparable和Comparator的类.这是什么意思?为什么我会使用一个而不是另一个?
我发现方法的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) 比方说你有一个Arraylist的HockeyPlayer对象.
如果他们都有一个变量int goalsScored你怎么能排序.你怎么能按目标排序呢?
java ×4
comparator ×2
sorting ×2
collections ×1
comparable ×1
comparison ×1
date ×1
integer ×1
optimization ×1
overflow ×1