- package TreeSet;
- import java.util.*;
- public class TreeSetEntrySet
- {
- public static void main(String[] args)
- {
- HashMap<Student,String> ma = new HashMap<Student,String>();
- //ma.put(new Student("zeng01",21),"beijing");
- ma.put(new Student("zeng01",21),"beijing");
- ma.put(new Student("zeng02",24),"wuhan");
- ma.put(new Student("zeng04",22),"zhengzhuo");
- ma.put(new Student("zeng03",23),"changshang");
- /*Set<Student> s = ma.keySet();
- for(Student stu:s)
- {
- String name= stu.getName();
- int age = stu.getAge();
- String value = ma.get(stu);
- sop(name+"...."+age+"..."+value);
- }*/
- Set<Map.Entry<Student, String>> entry = ma.entrySet();
- for(Iterator<Map.Entry<Student,String>> it = entry.iterator();it.hasNext();)
- {
- Map.Entry<Student,String> en = it.next();
- Student stu =en.getKey();
- String addr = en.getValue();
- sop(stu.getName()+"..."+stu.getAge()+"....."+addr);
- }
- }
- static void sop(Object obj)
- {
- System.out.println(obj);
- }
- }
- class Student implements Comparable<Student>
- {
- private String name;
- private int age;
- public Student(String name,int age)
- {
- this.name = name;
- this.age=age;
- }
- public String getName()
- {
- return this.name;
- }
- public int getAge()
- {
- return this.age;
- }
- public int compareTo(Student stu)
- {
- int num = age-stu.getAge();
- if(num==0)
- return name.compareTo(stu.getName());
- return num;
- }
- public int hashCode()
- {
- return name.hashCode()+age*17;
- }
- public boolean equals(Object obj)
- {
- if(obj instanceof Student)
- throw new RuntimeException("类型不同!!");
- Student stu = (Student)obj;
- return name.equals(stu.getName())&& age==stu.getAge();
- }
- }
复制代码 当存入重复键值对时运行时抛出如下异常:Exception in thread "main" java.lang.RuntimeException: 类型不同!!
at TreeSet.Student.equals(TreeSetEntrySet.java:76)
at java.util.HashMap.put(HashMap.java:475)
at TreeSet.TreeSetEntrySet.main(TreeSetEntrySet.java:10)
他是怎么抛出的
大家帮忙看看 谢谢了
|