- import java.util.*;
- class MapTest2
- {
- public static void main(String[] args)
- {
- TreeMap<Student,Address> tm = new TreeMap<Student,Address>();
- tm.put(new Student("蒙奇·D·路飞",19), new Address("东海"));
- tm.put(new Student("爱德华·纽盖特",72), new Address("新世界3"));
- tm.put(new Student("乔拉可尔·密佛格",43), new Address("新世界2"));
- tm.put(new Student("马尔高",32), new Address("新世界1"));
- tm.put(new Student("索隆",23), new Address("东海"));
- Set<Map.Entry<Student, Address>> entrySet = tm.entrySet();
- Iterator<Map.Entry<Student, Address>> it = entrySet.iterator();
- while(it.hasNext())
- {
- Map.Entry<Student, Address> me = it.next();
- Student key = me.getKey();
- Address value = me.getValue();
- System.out.println(key.getName()+".."+key.getAge()+".."+value.getAddress());
- }
- }
- }
- class Student implements Comparable<Student>//实现Comparable,复写其compareTo方法。
- {
- private String name;
- private int age;
- Student(String name, int age)
- {
- this.name = name;
- this.age = age;
- }
- public int compareTo(Student s)
- {
- int num = this.name.compareTo(s.name);
- if(num==0)
- {
- return new Integer(this.age).compareTo(new Integer(s.name));
- }
- return num;
- }
- public int hashCode() //复写哈希表数据结构的 hashCode方法
- {
- return this.name.hashCode()+age*21;
- }
- 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 getName()
- {
- return name;
- }
- public int getAge()
- {
- return age;
- }
- public String toString()
- {
- return name+":"+age;
- }
- }
- class Address
- {
- private String address;
- Address(String address)
- {
- this.address = address;
- }
- public String getAddress()
- {
- return address;
- }
- }
复制代码 以上代码,在编译之后出现了异常,看了许久也没找到问题在哪,求解。。编译结果如下图:
|