- import java.util.*;
- /*
- 需求:对学生对象的年龄进行升序排序。
- 因为数据是以键值对形式存在的,
- 要使用可以进行排序的Map集合。TreeMap
- */
- 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 num;
- }
- }
- class Test
- {
- public static void main(String[] args)
- {
- TreeMap<Student,String> tm =new TreeMap<Student,String>();
- tm.put(new Student("zhangsan",11),"bj");
- tm.put(new Student("lisi",31),"nj");
- tm.put(new Student("wangwu",21),"dj");
- tm.put(new Student("wangwu",21),"极乐世界");
- //方式1.
- Set<Student> keySet=tm.keySet();
- for (Iterator<Student> it =keySet.iterator(); it.hasNext(); )
- {
- Student key =it.next();
- String addr =tm.get(key);
- sop(key+".."+addr);
- }
- //方式2
- Set<Map.Entry<Student,String>> entry =tm.entrySet();
- for (Iterator<Map.Entry<Student,String>> it =entry.iterator();it.hasNext() ; )
- {
- Map.Entry<Student,String> e =it.next();
- //Student key =it.next().getKey();
- //String value =it.next().getValue();
- Student key =e.getKey();
- String value =e.getValue();
- sop(key+"----++++-------"+value);
- }
- }
- public static void sop(Object obj)
- {
- System.out.println(obj);
- }
- }
- class Student implements Comparable<Student>
- {
- private String name;
- private String address;
- private int 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*11;
- }
- 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;
- }
- Student(String name,int age)
- {
- this.name=name;
- this.age=age;
- }
- public String getName()
- {
- return name;
- }
- public int getAge()
- {
- return age;
- }
- public String toString()
- {
- return name+"---->"+age;
- }
- }
复制代码 |