本帖最后由 左建飞 于 2012-8-20 17:51 编辑
- package day16;
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.Map;
- import java.util.Set;
- import java.util.TreeMap;
- public class StudentMap
- {
- /**
- * @Map中装Student对象为key,相应地址为value。
- */
- public static void main(String[] args)
- {
- //HashMap<Student,String> hm=new HashMap<Student,String>();
- TreeMap<Student,String> tm=new TreeMap<Student,String>();
- tm.put(new Student("zhangsan01",20), "beijing");
- tm.put(new Student("zhangsan01",20), "beijing");
- tm.put(new Student("zhangsan01",20), "tianjin");
- tm.put(new Student("zhangsan02",22), "shanghai");
- tm.put(new Student("zhangsan03",23), "tianjin");
- Set<Map.Entry<Student,String>> hs=tm.entrySet();
- for(Iterator<Map.Entry<Student,String>> it=hs.iterator();it.hasNext();)
- {
- Map.Entry<Student, String> me=it.next();
- Student stu=me.getKey();
- String add=me.getValue();
- System.out.println(stu+"^"+add);
- }
- }
- }
- class Student implements Comparable<Student>
- {
- private String name;
- private int age;
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = 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(this.name));
- if(num==0)
- return this.name.compareTo(s.name);
- return num;
- }
- public int hashCode()//要重写hashCode方法。尽量让每个元素的返回值不同。
- {
- return this.name.hashCode()+age*10;
- }
- public boolean equals(Object obj)//重写equals方法。
- {
- if(!(obj instanceof Student))
- throw new ClassCastException("类型不匹配");
- Student s=(Student) obj;
- return this.name.equals(s.name)&&(this.age==s.age);
- }
- public String toString()//打印对象需要调用这个方法。
- {
- return this.name+":"+this.age;
- }
- }
复制代码 为什么使用HashMap时完全正常,一改为TreeMap就报错呀?各位高手帮我找找错误吧。
|