本帖最后由 騛鹏 于 2013-4-6 21:11 编辑
- import java.util.*;
- import java.util.TreeSet;
- 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("leixing bu pipei");
- 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 MapTest
- {
- public static void main(String[] args)
- {
- HashMap<Student,String> hm = new HashMap<Student,String>();
- hm.put(new Student("list1",21),"beijing");
- hm.put(new Student("list1",21),"tianjin");
- hm.put(new Student("list2",22),"shanghai");
- hm.put(new Student("list3",23),"nanjing");
- hm.put(new Student("list4",24),"wuhan");
- /* //第一种取出方式 :keySet
- //先获取map集合的所有键的Set集合,keySet();
- Set<Student> keySet = hm.keySet();
- //有了Set集合。就可以获取其迭代器。
- Iterator<Student> it = keySet.iterator();
-
- while (it.hasNext())
- {
- Student stu = it.next();
- //有了键可通过map集合get方法获取对应的值。
- String addr = hm.get(stu);
- System.out.println(stu+".."+addr);
- }
- */
- //第二种方式: EntrySet
- //将Map集合中的映射关系取出。存入到Set集合中
- Set<Map.Entry<Student,String>> entrySet = hm.entrySet();
-
- //TreeSet<Map.Entry<Student,String>> treeSet = new TreeSet<Map.Entry<Student,String>>(hm);
-
- 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();
- System.out.println(stu+"::::::::"+addr);
- }
- }
-
- }
复制代码 本例中如何使用TreeSet()排序?改动可以,关键是 以实现 compareble的方式来排序,而非定义比较器。
//TreeSet<Map.Entry<Student,String>> treeSet = new TreeSet<Map.Entry<Student,String>>(hm);
这句是错误的。
TreeSet(Collection<? extends E> c)
构造一个包含指定 collection 元素的新 TreeSet,它按照其元素的自然顺序进行排序。
为什么不可以? |