集合递增 o1 > o2(1) o1 == o2(0) o1 < o2(-1)
集合递减 o1 < o2(1) o1 == o2(0) o1 > o2(-1)
public class ComparatorDemo {
public static void main(String[] args) {
final List<Medal> medals = new ArrayList<Medal>();
medals.add(new Medal(8, "冠军"));
medals.add(new Medal(7, "亚军"));
medals.add(new Medal(9, "季军"));
Collections.sort(medals, new Comparator<Medal>() {
public int compare(Medal o1, Medal o2) {
if (o1.getCount() == o2.getCount()) {
return 0;
}
return o1.getCount() > o2.getCount() ? 1 : -1;
}
});
System.out.println(medals.toString());
}
}
class Medal {
private int count;
private String name;
public Medal() {}
public Medal(int count, String name) {
this.count = count;
this.name = name;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Medal [count=" + count + ", name=" + name + "]\n";
}
}
网友评论