本帖最后由 杨兴庭 于 2013-7-9 21:15 编辑
import java.util.*;
class StuNameComparator implements Comparator<Student>
{
public int compare(Student s1,Student s2)
{
int num=s1.getName().compareTo(s2.getName());
if(num==0)
return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
return num;
}
}
class MapTest2
{
public static void main(String[] args)
{
TreeMap<Student,String>tm=new TreeMap<Student,String>(new StuNameComparator());
tm.put(new Student("blisi3",23),"nanjing");
tm.put(new Student("lisil",21),"beijing");
tm.put(new Student("alisi4",24),"wuhan");
tm.put(new Student("lisi2",22),"shanghai");
Set<Map.Entry<Student,String>>entrySet=tm.entrySet();
Iterator<Map.Entry<Student,String>>it=entrySet.iterator();
while(it.hasNext())
{
Map.Entry<Student,String>me=it.next();
Student stu=me.getKey();
String addr=me.getValue();
System.out.println(stu+":::"+addr);
}
}
}
对于这段代码,我有些地方不是太明白,希望跟大家讨论下,解开我的困惑,其中TreeMap和HashMap有什么区别吗,为什么在TreeMap<Student,String>tm=new TreeMap<Student,String>(new StuNameComparator());和TreeMap<Student,String>tm=new TreeMap<Student,String>(new StuNameComparator());这两条语句之后,可以用相同的方法对Student中的数据进行处理,另外Set<Map.Entry<Student,String>>entrySet=tm.entrySet();这句代码如何理解,Iterator<Map.Entry<Student,String>>it=entrySet.iterator();这个迭代器是怎么使用的?
|