本帖最后由 张扬123 于 2012-8-20 15:38 编辑
不多说,先来代码。- import java.util.*;
- 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("类型不匹配");
- 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("lisi1",21),"beijing");
- hm.put(new Student("lisi1",21),"tianjin");
- hm.put(new Student("lisi2",22),"shanghai");
- hm.put(new Student("lisi3",23),"nanjing");
- hm.put(new Student("lisi4",24),"wuhan");
- Set<Student> keySet = hm.keySet();
- Iterator<Student> it = keySet.iterator();
- while (it.hasNext())
- {
- Student stu = it.next();
- String addr=hm.get(stu);
- System.out.println(stu+"..."+addr);
- }
- }
- }
- }
复制代码 把上面的一,二处的hashCode和equals删除之后,也就是没有复写,会出现两个lisi1都输出的情况。
再看下面的。没有复写,就不会出现两个。
这是为什么?- import java.util.*;
- class MapDemo
- {
- public static void main(String[] args)
- {
- Map<String,String> map = new HashMap<String,String>( );
- map.put("01","zhangsan1");
- map.put("01","wangwu");
- map.put("02","zhangsan2");
- map.put("03","zhangsan3");
-
- Collection<String> coll=map.values();
- System.out.println(map);
- }
- }
复制代码 |