0
我想按降序排列列表對象,並面臨classCastException。對象列表降序排列
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
class Student implements Comparator<Student>{
private int id;
private String name;
public Student(int id, String name){
this.id = id;
this.name = name;
}
public int getId(){
return id;
}
public String getName(){
return name;
}
}
public class CollectionSearchDemo {
public static void main(String[] args) {
List<Student> list = new ArrayList<Student>();
list.add(new Student(3, "ouier"));
list.add(new Student(2, "fdgds"));
list.add(new Student(7, "kiluf"));
list.add(new Student(1, "6trfd"));
list.add(new Student(8, "hjgas"));
list.add(new Student(5, "ewwew"));
Collections.sort(list, new Comparator<Student>() {
@Override
public int compare(Student arg0, Student arg1) {
return arg0.getId() - arg1.getId();
}
});
Iterator iterator = list.iterator();
while(iterator.hasNext()){
Student student = (Student) iterator.next();
System.out.print(student.getId()+":"+student.getName()+" ");
}
System.out.println("\nSorting in reverse order:");
// Collections.reverse(list);
Comparator<Student> collections = Collections.reverseOrder();
Collections.sort(list, collections); // here getting classCastException.
Iterator iterator1 = list.iterator();
while(iterator1.hasNext()){
Student student = (Student) iterator1.next();
System.out.print(student.getId()+":"+student.getName()+" ");
}
}
}
想知道幾個thigs。 1)有什麼區別bet'n Collection.reverse(list) and Comparator collections = Collections.reverseOrder(); Collections.sort(list,collections); 2)爲什麼我面臨classCastException。
你得到一個'ClassCastException'因爲'Student'應該實現可比'',不'比較'。 –
2013-02-14 23:22:52
yes.it works.Can你請讓我知道更多的描述嗎?它會幫助我更好地理解這個概念 – nakul 2013-02-14 23:37:23
'比較器'比較事情。 「比較」可以與其他事物相比較。 – 2013-02-14 23:40:58