对于没有实现Comparable的,我们就用Object,按照hashCode大小来排序.
List list= new ArrayList();
list.add(new Object());
list.add(new Object());
list.add(new Object());
Collections.sort(list,new Comparator(){ public int compare(Object o1, Object o2){
return (o1.hashCode()-o2.hashCode());
})
例程:自己写了两个类,根据Comparable接口来实现的
User对象
public class User implements Comparable<User>{
private String name = "";
private int age = 0;
public User(String name,int age){
this.name = name;
this.age = age;
}
public int compareTo(User anotherUser) {
return this.age > anotherUser.getAge()? 1:this.age == anotherUser.getAge()?0:-1;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString(){
return "user name = " + this.name + ", age = " + this.age;
}
}