class MapTest
{
public static void main(String[] args)
{
HashMap<Student,String> hm = new HashMap<Student,String>();
hm.put(new Student("lisi1",11),"beijing");
hm.put(new Student("lisi2",11),"shangahi");
hm.put(new Student("lisi3",11),"nanjing");
hm.put(new Student("lisi4",11),"wuhan");
//第一种 keySet
Set<Student> keyset = hm.keySet();
Iterator<Student> it = keyset.iterator();
while (it.hasNext())
{
Student s = it.next();
String add = hm.get(s);
System.out.println("key:"+s+",value:"+add);//key:lisi3,value:nanjing//key值返回的为什么是名字,不应该是一个对象的地址值么?
}
}
}
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*7; }
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; }}
|