import java.util.*;
class Student implements Comparable
{
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;//這裡可不可以寫成 return this.name == s.name &&this.age==s.age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public String toString()
{
return name+":"+age;
}
}
class MapTest
{
public static void main(String[] args)
{
HashMap hm = new HashMap();
hm.put(new Student("lisi1",21),"beijing");
hm.put(new Student("lisi2",22),"shanghai");
hm.put(new Student("lisi3",23),"nanjign");
hm.put(new Student("lisi4",24),"wuhan");
hm.put(new Student("lisi5",25),"changsha");
//第一種取出方式 keySet
System.out.println("第一種方式");
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);
}
System.out.println("第二種方式");
//第二種取出方式
Set<Map.Entry<Student,String>> entrySet = hm.entrySet();
Iterator<Map.Entry<Student,String>> it1 = entrySet.iterator();
while(it1.hasNext())
{
Map.Entry<Student,String> me = it1.next();
Student stu = me.getKey();
String addr = me.getValue();
System.out.println(stu+"..."+addr);
}
}
}
//Student類中復寫equals方法 比較名字的時候可不可以把equals換成==呢??
String是一個對象,==表示是兩個對象是同一個對象,指向同一塊內存地址,A.equals(B)表示A的值和B的值相同即可,兩者表示的含義不同,所以我認為這裡不能換成==