本帖最后由 孙百鑫 于 2013-6-19 09:04 编辑
- 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 String getName()
- {
- return name;
- }
- public int getAge()
- {
- return age;
- }
- public int compareTo(Student s)
- {
- if (this.getName().compareTo(s.getName()) == 0)
- {
- return this.getAge() - s.getAge();
- }
- return this.getName().compareTo(s.getName());
-
- }
- 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;
- }
- }
- class MapTest2
- {
- public static void main(String[] args)
- {
- HashMap<Student,String> map = new HashMap<Student,String>();
- map.put(new Student("zhangsan1",20),"beijing1");
- map.put(new Student("zhangsan2",21),"beijing2");
- map.put(new Student("zhangsan3",22),"beijing3");
- map.put(new Student("zhangsan4",23),"beijing4");
- map.put(new Student("zhangsan3",22),"beijing3");
- map.put(new Student("zhangsan4",23),"beijing4");
- Set<Student> ts = map.keySet();
- for (Iterator<Student> it = ts.iterator() ;it.hasNext() ; )
- {
- Student stu = it.next();
- System.out.println("name:" + stu.getName() + ",age:" + stu.getAge() + ",addr:" + map.get(stu) );
- }
- /*
- Set<Map.Entry<Student,String>> ts = map.entrySet();
- for (Iterator<Map.Entry<Student,String>> it = ts.iterator() ;it.hasNext() ; )
- {
- Map.Entry<Student,String> me = it.next();
- System.out.println("name:" + me.getKey().getName() + ",age:" + me.getKey().getAge() + ",addr:" + me.getValue() );
- }
- }
- }
复制代码 自己敲了一边发现编译能够通过,但是不能消除重复。又重新看了下视频,发现Student类中的比较方法跟老师写的基本一样,实在是找不出原因。求教各位帮帮忙? |