public boolean equals(Object obj)//此处复写了equals方法,如果使用HashSet集合,需要调用此方法
{
if (!(obj instanceof Student))
return false;
Student s =(Student)obj;
return this.name.equals(s.name) && this.age==s.age;
}
public int hashCode()//此处复写了hashCode方法,如果使用HashSet集合,需要调用此方法
{
return this.name.hashCode()+this.age*23;
}
public int compareTo(Object obj)//复写compareTo方法,让元素自身具备比较性(先比name,如果一致,比较age)
{
if (!(obj instanceof Student))
throw new RuntimeException("不是学生对象");
Student s =(Student)obj;
if (this.name.equals(s.name))
{
Integer tage=this.age;
Integer sage=s.age;
return tage.compareTo(sage);
}
return this.name.compareTo(s.name);
}
public String getName()//获取name
{
return name;
}
public int getAge()//获取age
{
return age;
}
}
class MyCompare implements Comparator//自定义比较器,若元素自带比较功能不适用,可适用自定的比较方法(先比age,如一致,再比name)
{
public int compare(Object o1,Object o2)
{
Student s1=(Student)o1;
Student s2=(Student)o1;
Integer i1=s1.getAge();
Integer i2=s2.getAge();
int num= i1.compareTo(i2);
if (num==0)
return s1.getName().compareTo(s2.getName());
return num;
}
}