代码如下:
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;
}
public int hashCode()
{
return name.hashCode()+age*35;
}
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 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 String getName()
{
return name;
}
public int getAge()
{
return age;
}
public String toString()
{
return name+"..."+age;
}
}
class MapEntryDemo
{
public static void main(String[] args)
{
HashMap<Student,String> stu= new HashMap<Student,String>();
stu.put(new Student("小遥",8),"三年级");
stu.put(new Student("小豪",6),"一年级");
stu.put(new Student("小程",2),"家里蹲");
stu.put(new Student("小明",9),"六年级");
stu.put(new Student("小露",12),"七年级");
Set<Student> keyset=stu.keySet();
Iterator<Student> it =stu.iterator();
while(it.hasNext())
{
Student key=it.next();
String grate=stu.get(key);
System.out.println(grate+key);
}
Set<Map.Entry<Student,String>> entryset=stu.entrySet();
Iterator<Map.Entry<Student,String>> iter=entryset.iterator();
while(iter.hasNext())
{
Map.Entry<Student,String> me=iter.next();
System.out.println(me.getKey()+ me.getValue());
}
}
}
编译不通过啊。。 |