import java.util.*;
class Student
{
private String name;
private int age;
Student(String name,int age)
{
this.name = name;
this.age = age;
}
public int hasCode()
{
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;
}
}
class StuNameComparator 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 num;
}
}
class StuAgeComparator implements Comparator<Student> //年龄比较器
{
public int compare(Student s1,Student s2)
{
int num = new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
if (num==0)
return s1.getName().compareTo(s2.getName());
return num;
}
}
class MapTest2
{
public static void main(String[] args)
{
//Scanner sc = new Scanner(System.in);
//sop("请选择排序方式:1.按年龄排序 2.按姓名排序");
//Integer s = sc.nextInt();
//问题:这里应该怎么写可以让用户自定义排序方式,请大神指教
TreeMap<Student,String> tm = new TreeMap<Student,String>(new StuNameComparator());
tm.put(new Student("lisi1",45),"beijing");
tm.put(new Student("lisi2",21),"shanghai");
tm.put(new Student("lisi3",25),"shenzhen");
tm.put(new Student("lisi8",18),"chaoyan");
tm.put(new Student("lisi4",33),"chengdu");
tm.put(new Student("lisi6",11),"wuhan");
Set<Map.Entry<Student,String>> entrySet = tm.entrySet();
Iterator<Map.Entry<Student,String>> it = entrySet.iterator();
while(it.hasNext())
{
Map.Entry<Student,String> me = it.next();
Student stu = me.getKey();
String addr = me.getValue();
sop(stu+".............."+addr);
}
}
public static void sop(Object obj)
{
System.out.println(obj);
}
} |
|