import java.util.*;
class StuNameCompare implements Comparator<Student>//此处为什么继承Comparator接口?{ public int compare(Student s1,Student s2)
{
int num=s1.getName().compareTo(s2.getName());
if(num==0)
return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
return num;
}
}
class Maptest2
{
public static void main(String[] args)
{
TreeMap<Student,String> tm=new TreeMap<Student,String>(new StuNameCompare());
tm.put(new Student("lisi1",21),"beiing");
tm.put(new Student("lisi2",20),"beiijng");
tm.put(new Student("lisi3",24),"beiwwing");
tm.put(new Student("lisi4",25),"beiinfg");
Set<Map.Entry<Student,String>> entrySet=tm.entrySet();
Iterator<Map.Entry<Student,String>> iter=entrySet.iterator();
while(iter.hasNext())
{
Map.Entry<Student,String> me=iter.next();
Student stu=me.getKey();
String addr=me.getValue();
System.out.println("key:"+stu+",value:"+addr);
}
}
}
class Student implements Comparable<Student>//此处为什么继承Comparable接口?{ private String name;
private int age;
Student(String name,int age)
{
this.name=name;
this.age=age;
}
public int compareTo(Student s)
{
int num=new Integer(this.age).compareTo(new Integer(s.age));
if(num==0)
return this.name.compareTo(s.name);
return num;
}
public int hashCode()
{
return name.hashCode()+age*34;
}
public boolean equals(Object obj)
{
if(!(obj instanceof Student))
throw new ClassCastException("类型不匹配");
Student s=(Student)obj;
return this.name.equals(s.name)&&this.age==s.age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public String toString()
{
return name+":"+age;
}
}
当我们继成这两个接口时,要重写哪些方法?
|