import java.util.*;
class MapTest2
{
public static void main(String[] args)
{
HashMap<Student,String> hmap=new HashMap<Student,String>();
hmap.put(new Student("张三",21),"北京");
hmap.put(new Student("李四",18),"上海");
hmap.put(new Student("王五",26),"广州");
hmap.put(new Student("abc",21),"南京");
Set<Map.Entry<Student,String>> entryset=hmap.entrySet();
Iterator<Map.Entry<Student,String>> it=entryset.iterator();
while(it.hasNext())
{
Map.Entry<Studengt,String> ma=it.next();
Student stu=ma.getKey();
String addr=ma.getValue();
System.out.println(stu+"::地址:"+addr);
}
}
}
class Student implements Comparable<Student>
{
private String name;
private int age;
public Student(String name,int age)
{
this.name=name;
this.age=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*12;
}
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;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public String toString()
{
return "姓名:"+name+":年龄:"+age;
}
}
编译时,出现的错误是
|
-
1.png
(2.45 KB, 下载次数: 20)
错误提示
|