问题描述
假设您有 Arraylist
的 HockeyPlayer
对象。
如果他们都有一个变量 int goalsScored ,如何排序呢?
您可以使用与自定义。
class HockeyPlayer {
public final int goalsScored;
// ...
};
List< HockeyPlayer> players = // ...
Collections.sort(players,new Comparator< HockeyPlayer>(){
@Override public int compare(HockeyPlayer p1,HockeyPlayer p2){
return p1.goalsScored - p2.goalsScored; // Ascending
}
});或者,您可以使 HockeyPlayer implements
a href =http://java.sun.com/javase/6/docs/api/java/lang/Comparable.html =nofollow noreferrer> 可比较的< HockeyPlayer>
。这为所有 HockeyPlayer
对象定义自然顺序。使用比较器
更灵活,因为不同的实现可以按名称,年龄等进行排序。
/ h3>
-
Lets say you have an Arraylist
of HockeyPlayer
objects.
How could you sort that if they all have a variable int goalsScored. How could you sort them by goalsScored?
解决方案 You can use Collections.sort
with a custom Comparator<HockeyPlayer>
.
class HockeyPlayer {
public final int goalsScored;
// ...
};
List<HockeyPlayer> players = // ...
Collections.sort(players, new Comparator<HockeyPlayer>() {
@Override public int compare(HockeyPlayer p1, HockeyPlayer p2) {
return p1.goalsScored - p2.goalsScored; // Ascending
}
});
Alternatively, you can make HockeyPlayer implements
Comparable<HockeyPlayer>
. This defines the natural ordering for all HockeyPlayer
objects. Using a Comparator
is more flexible in that different implementations can order by name, age, etc.
See also
For completeness, I should caution that the return o1.f - o2.f
comparison-by-subtraction shortcut must be used with extreme caution due to possible overflows (read: Effective Java 2nd Edition: Item 12: Consider implementing Comparable
). Presumably hockey isn't a sport where a player can score goals in the amount that would cause problems =)
See also
这篇关于如何通过属性对对象的数组列表排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!