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()+" ");
}
}
}
몇 가지 치고 알아야 할 것이 있습니다. 1) 차이점은 무엇입니까? Collection.reverse (목록) 및 Comparator collections = Collections.reverseOrder(); Collections.sort (list, collections); 2) 왜 classCastException이 발생했는지.
는'때문에 Student'가 구현해야'대등'이 아닌'비교기 '. –
예. 작동합니다. 좀 더 자세히 설명해 주시겠습니까?이 개념을 더 잘 이해하는 데 도움이 될 것입니다. – nakul
'비교 자'는 물건을 비교합니다. 'Comparable'은 다른 것들과 비교 될 수 있습니다. –