本帖最后由 杨兴庭 于 2013-7-9 11:21 编辑
import java.util.*;
class MapTest
{
public static void main(String[] args)
{
HashMap<Student,String>hm=new HashMap<Student,String>();
hm.put(new Student("lisi1",21),"beijing");
hm.put(new Student("lisi2",22),"shanghai");
hm.put(new Student("lisi3",23),"nanjing");
hm.put(new Student("lisi4",24),"wuhan");
//第一种取出方式 keySet
Set<Student>keySet=hm.keySet();
Iterator<Student>it=keySet.iterator();
while(it.hasNext())
{
Student stu=it.next();
String addr=hm.get(stu);
System.out.println(stu+"...."+addr);
}
//第二种取出方式entrySet
Set<Map.Entry<Student,String>>ite=entrySet.iterator();
Iterator<Map.Entry<Student,String>>iter=entrySet.iterator();
while(iter.hasNext())
{
Map.Entry<Student,String>me=iter.next();
Student stu=me.getKey();
String addr=me.getValue();
System.out.println(stu+"..."+addr);
}
}
}
class Student implements Comparable<Student>
{
private String name;
private int age;
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*34;
}
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;
}
}
对于这段代码,我有几个问题不解, Set<Student>keySet=hm.keySet(); Iterator<Student>it=keySet.iterator();这两句连起来怎么理解,分开又怎么理解? return name.hashCode()+age*34;这句又是什么,怎么还要加一个age*34这么一个东东呀?另外this.age==s.age;中的this和s分别是怎么样更容易理解,在进行调用比较时,this和s又分别指的什么时候添加进去的对象?
|