我有自定义对象,例如person。每个人都有一个等级,社交号码和积分。什么是通过积分对人进行排序并对其进行排名的最有效方式。我应该使用什么 - 比较器,映射或覆盖某些列表的添加方法?如何以最有效的方式制作?
答案 0 :(得分:0)
package main;
public class Person implements Comparable<Person> {
private final String rank;
private final int points;
public Person(String rank, int points) {
this.rank = rank;
this.points = points;
}
public String rank() {
return rank;
}
public int points() {
return points;
}
public boolean equals(Object o) {
if (!(o instanceof Person))
return false;
Person person = (Person) o;
return person.rank.equals(rank) && person.points == points;
}
// public int hashCode() {
// return your hash;
// }
public String toString(){
return "Rank: " + rank +", points = " + points ;
}
public int compareTo(Person person) {
return points > person.points ? 1 : points < person.points ? -1 : 0;
}
}
然后测试
public static void main(String[] args) {
Person usersArray[] = { new Person("RankX", 1), new Person("RankY", 100),
new Person("RankZ", 44), new Person("RankF", 21) };
List<Person> users = Arrays.asList(usersArray);
Collections.sort(users);
System.out.println(users);
Collections.sort(users, Collections.reverseOrder());
System.out.println(users);
}
输出
[Rank:RankX,points = 1,Rank:RankF,points = 21,Rank:RankZ,points = 44,等级:RankY,points = 100]
[Rank:RankY,points = 100,Rank:RankZ, points = 44,Rank:RankF,points = 21,Rank:RankX,points = 1]