本帖最后由 黑马连家华 于 2012-8-13 17:24 编辑
/*
存入学生对象(成员有name和age),要求对应所在班级存储
*/
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 String getName()
{
return name;
}
public int getAge()
{
return age;
}
public int hashCode()
{
return this.name.hashCode()+this.age*13;
}
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;
}
public int compareTo(Student stu)
{
int num = this.name.compareTo(stu.name);
if (num == 0)
{
return new Integer(this.age).compareTo(new Integer(stu.age));
}
return num;
}
}
class Exercise4
{
public static void main(String[] args)
{
//建立集合这个集合里面是教室和学生对象
TreeMap<String,Student> classes = new TreeMap<String,Student>();
classes.put("Base",new Student("ZhanSan",18));
classes.put("Base",new Student("LiSi",22));
classes.put("Adv",new Student("Wangwu",25));
classes.put("Adv",new Student("ZhaoLiu",22));
//取出教室与学生的关系
Set<Map.Entry<String,Student>> es = classes.entrySet();
for (Iterator<Map.Entry<String,Student>> it = es.iterator();it.hasNext() ; )
{
Map.Entry<String,Student> me = it.next();
//取出教室,并打印
System.out.println(me.getKey());
//然后如何使用迭代器取出教室里的学生????????????
}
}
}
|