本帖最后由 如梦初醒 于 2012-4-13 09:50 编辑
/**
*我看了一下这个程序,觉得代码有些重复还没有说明比较的方式,于是将代码精简了一下,并修改了
*输入信息,运行结果正常,jvm环境设好后,可直接运行,你可试试。
*/
import java.util.*;
class StuNameCompare implements Comparator<Student>
{
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 s1.getAge()-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),"beijing");
tm.put(new Student("lisi2",20),"beiijng");
tm.put(new Student("lisi1",24),"beiwwing");
tm.put(new Student("lisi2",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>
{
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;
}
}
运行结果:
|
|