标题: 大神们帮忙看看哪来那么多错误啊 [打印本页] 作者: 走遍世界找寻你 时间: 2013-8-11 10:54 标题: 大神们帮忙看看哪来那么多错误啊 import java.util.*;
class Student implements Comparable<Student>
{
private String name;
private int age;
Student(String name,String age)
{
this.name = name;
this.age = age;
}
public int compareTo(Student s)
{
int num = new Integer(this.age).compareTo(s.name);
return num;
}
public int hashCode()
{
return name.hashCode()+age*20;
}
public boolean equals(Object obj)
{
if (!obj instanceof Student)
{
throw new ClassCastException("leixingcuowu");
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 Hash<Student,String>();
hm.put(new Student("lisi1",21),"beijing");
hm.put(new Student("lisi2",22),"beijing");
hm.put(new Student("lisi3",23),"beijing");
hm.put(new Student("lisi4",24),"beijing");
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);
}
}
} 作者: 狐灵 时间: 2013-8-11 11:19 本帖最后由 狐灵 于 2013-8-11 11:20 编辑
①
private String name; private int age; Student(String name,String age)
{
this.name = name; this.age = age;
}
申明了一个int型的age,然后在构造方法中传进去一个String的age,报错:类型不兼容。
②
public int compareTo(Student s)
{
int num = new Integer(this.age).compareTo(s.name);
return num;
}
Integer中有public int compareTo(Integer anotherInteger)方法, 你传一个String过去做参数,报错:无法将java.lang.Integer中的compareTo(java.lang.Integer)应用于java.lang.String.
话说拿age和name比较,这是要干什么呢?
③ HashMap<Student,String> hm = new Hash<Student,String>(); 有找不到Hash这个类,不应该报错么?
④ public boolean equals(Object obj)
{ if (!obj instanceof Student)
{
throw new ClassCastException("leixingcuowu");
Student s = (Student)obj;
return this.name.equals(s.name) && this.age==s.age;
}
}
if (!obj instanceof Student)这个!直接就作用在obj上了,靠谱么?是不是应该给个括号~!? 作者: 神之梦 时间: 2013-8-11 15:01
代码最好用放在“<>”这个里边,方便别人复制,另外最好将错误信息贴出
还有一点建议就是,不要看到一大片错误就头懵,一个一个自己去找,收获会更大,找不出再来论坛求助会更好作者: sergio 时间: 2013-8-11 17:12
修改如下,有什么问题存在还可继续探讨。有错误和有点不适合的地方已经用注释标注。最后附上一张hash表的结构图(来自动力节点)。
package com.sergio.Thread;
/**
* @ClassName: Test06
* @Description: TODO(这里用一句话描述这个类的作用)
* @author Sergio Han
* @date 2013-8-11 下午4:16:06
*
*/
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;
// }
//此处也是写错
Student(String name, int age)
{
this.name = name;
this.age = age;
}
// public int compareTo(Student s) {
// int num = new Integer(this.age).compareTo(s.name);