import java.util.*;
class Student implements Comparable<Student>
{
private String name;
private int age;
public int hashCode()
{
return name.hashCode()+age*30;
}
public boolean equals(Object obj)
{
if (!(obj instanceof Student))
{
throw new ClassCastException("传进的不是学生类型");
}
Student stu=(Student)obj;
return this.name.equals(stu.name)&&this.age==stu.age;
//return this.toString()==stu.toString();
}
public int compareTo(Student s)
{
int x=new Integer(this.age).compareTo(new Integer(s.age));
if (x==0)
{
return this.name.compareTo(s.name);
}
return x;
}
public void SetName(String name)
{
this.name=name;
}
public String GetName()
{
return name;
}
public void SetAge(int age)
{
this.age=age;
}
public int GetAge()
{
return age;
}
public String toString()
{
return "Student"+this.GetName()+"\t"+this.GetAge();
}
public Student(String name,int age)
{
this.name=name;
this.age=age;
}
}
class StudentDemo
{
public static void main(String[] args)
{
HashMap<Student,String> hp=new HashMap<Student,String>();
hp.put(new Student("张三",29),"北京");
hp.put(new Student("李四",30),"上海");
hp.put(new Student("王五",31),"深圳");
Set<Student> s=hp.keySet();
Iterator<Student> in=s.iterator();
while (in.hasNext())
{
Student stu=in.next();
String str=hp.get(stu);
System.out.println(stu+"\t"+str);
}
Set<Map.Entry<Student,String>> set=hp.entrySet();
Iterator iter=set.iterator();
while (iter.hasNext())
{
Map.Entry<Student,String> map=iter.next(); //提示说iter.next();不兼容类型,没找到为什么希望能帮我找下错误谢谢。
Student xs=map.getKey();
String add=map.getValue();
System.out.println(xs+add);
}
}
}
|