import java.util.*;
class Student implements Comparable<Student>
{
String name;
int age;
public int compareTo(Student s)
{
int num=new Integer(this.age).compareTo(new Integer(s.age));
if(num==0)
return this.name.compareTo(s.name);
return num;
}
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;
}
Student(String name,int age)
{
this.name=name;
this.age=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> hs=new HashMap<Student,String>();
hs.put(new Student("lm",21),"shanghai");
hs.put(new Student("lm",22),"beijing");
hs.put(new Student("lm",23),"shenzhne");
hs.put(new Student("lm",24),"tianjing");
//第一种
Set<Student> keyset=hs.keySet();
Iterator<Student> it=keyset.iterator();
while(it.hasNext())
{
Student stu=it.next();
String addr=hs.get(stu);
System.out.println(stu+"...."+addr);
}
//第二种
Set<Map.Entry<Student,String>> entrySet=hs.entrySet();
Iterator<Map.Entry<Student,String>> iter=entrySet.iterator();
while(iter.hasNext())
{
Map.Entry<Student,String> me=iter.next();
Student stu=me.getKey();
String addr=me.getValue();
System.out.println(stu+"...."+addr);
}
}
}
出现的问题:
C:\100>javac MapTest.java
MapTest.java:15: 找不到符号
符号: 方法 hashcode()
位置: 类 java.lang.String
return name.hashcode()+age*34;
^
MapTest.java:15: 运算符 + 不能应用于 java.lang.String.hashcode,int
return name.hashcode()+age*34;
^
MapTest.java:15: 不兼容的类型
找到: <nulltype>
需要: int
return name.hashcode()+age*34;
^
3 错误
C:\100> |
|