实在查不出哪出问题了,equals应该要运行啊!!!
import java.util.*;
class StudentTest
{
public static void main(String[] args)
{
List<Student> all = new ArrayList<Student>();
all.add(new Student("张三","No:01",98.1));
all.add(new Student("李四","No:02",92.3));
all.add(new Student("刘七","No:05",76.4));
all.add(new Student("王五","No:04",78.5));
all.add(new Student("刘七","No:05",77.4));
all.add(new Student("周六","No:03",66.3));
all.add(new Student("刘七","No:05",77.4));
MyCompare comparator = new MyCompare();
Collections.sort(all,comparator);
for (Student s:all )
{
System.out.println(s.toString());
}
}
}
//定义一个学生类
class Student
{
private String name;
private String id;
private double grade;
Student(String name,String id,double grade)
{
this.name = name;
this.id = id;
this.grade = grade;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
public double getGrade()
{
return grade;
}
public void setGrade(double grade)
{
this.grade = grade;
}
//覆写Object类中的toString()方法
public String toString()
{
return "学生姓名:"+this.name+"\t学生编号:"+this.id+"\t学生成绩:"+this.grade;
}
//覆写equals方法
public boolean equals(Object obj)
{
if(!(obj instanceof Student))
throw new ClassCastException("类型不匹配");
Student s=(Student)obj;
return this.name.equals(s.name)&&this.id.equals(s.id);
}
}
//比较器
class MyCompare implements Comparator<Student>
{
public int compare(Student s1,Student s2)
{
int num = s1.getId().compareTo(s2.getId());
if(num==0)
{
return new Double(s1.getGrade()).compareTo(new Double(s2.getGrade()));
}
return num;
}
}
|
|