黑马程序员技术交流社区
标题:
关于 TreeMap 练习中的问题
[打印本页]
作者:
黄长利
时间:
2012-4-2 17:49
标题:
关于 TreeMap 练习中的问题
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;
}
}
复制代码
以上代码,在编译之后出现了异常,看了许久也没找到问题在哪,求解。。编译结果如下图:
选择排序.jpg
(41.21 KB, 下载次数: 49)
下载附件
2012-4-2 17:49 上传
作者:
如梦初醒
时间:
2012-4-2 18:37
public int compareTo(Student s)
35. {
36. int num = this.name.compareTo(s.name);
37. if(num==0)
38. {
39. return new Integer(this.age).compareTo(new Integer(s.name));//
这个地方出错了
40. }
41. return num;
42. }
return new Integer(this.age).compareTo(new Integer(s.name));
这行代码有问题,new Integer(s.name),s.name是字符串,应改为
new Integer(s.age)
作者:
孙利川
时间:
2012-4-2 18:42
第39行代码出错
作者:
adison
时间:
2012-4-2 19:02
39行代码写错了,
return new Integer(this.age).compareTo(new Integer(s.name));
改为
return new Integer(this.age).compareTo(new Integer(s.age));
new Integer(s.name)这句代表着把字符串s.name转为一个Integer对象,但s.name 不是可解析的整数,所以会发生NumberFormatException异常
当你试图将字符串转换成一种数值类型,但该字符串不能转换为适当格式时,就会抛出该异常
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2