如果你的类是一个基础类,需要比较该类的对象是否相同时必须覆盖equals和hashcode方法
package com.io;
/**
* 学生类
* @author 黑马_王康
*
*/
public class Student implements Comparable<Student>{
private String name;
private int mt,cn,en;
private int sum;
Student( String name,int mt,int cn,int en){
this.name = name;
this.mt = mt;
this.cn = cn;
this.en = en;
sum = mt + cn + en;
}
public String getName(){
return name;
}
public int getSum(){
return sum;
}
public int getEn(){
return en;
}
public int getCn(){
return cn;
}
@Override
public int compareTo(Student stu) { //实现compareTo方法
int num = new Integer(this.sum).compareTo(new Integer(stu.sum));
if(num == 0){
return this.name.compareTo(stu.name);
}
return num;
}
public int hashCode(){ //覆盖hashCode方法
return name.hashCode()+sum*66;
}
public boolean equals(Object obj){ //覆盖equals方法
if(!(obj instanceof Student))
throw new ClassCastException("类型不匹配");
Student stu = (Student)obj;
return this.name.equals(stu.name)&&this.sum==stu.sum;
}
public String toString(){ //重写toString方法
return "student["+name+","+mt+","+cn+","+en+"]";
}
} |