代码如下:Student类:public class Student implements Comparable<Student> { private String id;//学生ID private String name;//学生姓名public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; }public void setName(String name) { this.name = name; }自定义的一个比较方法:public class StudentComparator implements Comparator<Student> { @Override public int compare(Student a, Student b) { // TODO Auto-generated method stub return a.getName().compareTo(b.getName()); }}实现排序的方法:public void testSort4(){ List<Student> liststudent = new ArrayList<Student>(); Student[] student = {new Student(),new Student(),new Student()}; student[0].setId(3+""); student[1].setId(1+""); student[2].setId(2+""); student[0].setName("Mike"); student[1].setName("JACK"); student[2].setName("Ace"); liststudent.addAll(Arrays.asList(student)); System.out.println("-----排序前-----"); for (Student student2 : student) { System.out.println("学生:"+student2.getId()+","+student2.getName()); } Collections.sort(liststudent, new StudentComparator()); System.out.println("-----排序后-----"); for (Student student2 : student) { System.out.println("学生:"+student2.getId()+","+student2.getName()); } }排序前后并无变化。。思考了很久想不明白错在哪?求给位大神告诉我原因!还有一点就是以下代码实行的时候会抛出一个空指针异常,我查了以下原因是没有初始化对象?Student[] student = new Student[3];student[0].setId("1");System.out.println(student[0].getId());希望大神能帮我解决这些疑惑,谢谢大家了。
添加回答
举报
0/150
提交
取消