- import java.util.*;
- class Student implements Comparable<Student>
- {
- private String name;
- private int no;
- Student(int no,String name)
- {
- this.no = no;
- this.name = name;
- }
- public int compareTo(Student s)
- {
- int num = new Integer(this.no).compareTo(new Integer(s.no));
- if (num==0)
- {
- return this.name.compareTo(s.name);
- }
- return num;
- }
- public int hashCode()
- {
- return 1;
- }
- public boolean equals(Object obj)
- {
- if(!(obj instanceof Student))
- throw new ClassCastException("您输入的与所需类型不匹配");
- Student s =(Student)obj;
- return this.no==s.no && this.name.equals(s.name);//
- }
- public String getName()
- {
- return name;
- }
- public int getNo()
- {
- return no;
- }
- public String toString()
- {
- return "no:"+no+" name:"+name;
- }
- }
- class StudentNoComparator implements Comparator<Student>
- {
- public int compare(Student s1,Student s2)
- {
- return s1.compareTo(s2);
- }
- }
- class Noname3
- {
- public static void main(String[] args)
- {
- TreeMap<Student,Integer> hm = new TreeMap<Student,Integer>(new StudentNoComparator());//
- hm.put(new Student(04,"student4"),24);
- hm.put(new Student(02,"student2"),22);
- hm.put(new Student(03,"student3"),23);
- hm.put(new Student(01,"student1"),21);
- hm.put(new Student(05,"student5"),25);
- System.out.println();
- Set<Map.Entry<Student,Integer>> entrySet = hm.entrySet();
- Iterator<Map.Entry<Student,Integer>> iter = entrySet.iterator();
- while (iter.hasNext())
- {
- Map.Entry<Student,Integer> me = iter.next();
- Student stu = me.getKey();
- Integer age = me.getValue();
- System.out.println(stu+" age:"+age);
- }
- }
- }
复制代码
|
|