在java中 在对集合对象和数据对象进行排序时,往往通过实现Comparator接口,下面看一个例子。
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
public class TestComparator implements Comparator<Object>{
@Override
public int compare(Object o1, Object o2) {
// TODO Auto-generated method stub
User user1 = (User)o1;
User user2 = (User)o2;
return user2.value - user1.value;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
List<User> list = new ArrayList<User>();
for(int i=0 ; i<5 ; i++){
list.add(new User("a" + new Random().nextInt(20), new Random().nextInt(20)));
}
TestComparator t = new TestComparator();
Collections.sort(list, t);
Iterator<User> it = list.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}
class User{
String name = null;
Integer value = 0;
public User(String name , Integer value){
this.name = name;
this.value = value;
}
@Override
public String toString() {
return "User [name=" + name + ", value=" + value + "]";
}
}
在实现Comparator接口的重写compare(Object o1,Object o2)方法的时候,如果返回的事o1.***-o2.***那么排序的结果就是从小到大排序,反之从大到小排序。