import java.util.*; 
class Person implements Comparable<Person> 
{ 
 private String name; 
 private int age; 
 Person(String name,int age) 
 { 
  this.name=name; 
  this.age=age; 
 } 
 public String getName() 
 { 
 return name; 
 } 
 public int getAge() 
 { 
 return age; 
 } 
 public int hashCode() 
 { 
 return name.hashCode()+age*23; 
 } 
 public boolean equals(Object obj) 
 { 
 if(!(obj instanceof Person)) 
  throw new ClassCastException("类型错误"); 
 Person p=(Person)obj; 
 return this.name.equals(p.name)&&this.age==p.age; 
 } 
 public int compareTo(Person p) 
 { 
 int num=new Integer(this.age).compareTo(new Integer(p.age)); 
 if(num==0) 
  return this.name.compareTo(p.name); 
  
 return num;   
 }  
    public String toString() 
 { 
 return name+".."+age; 
 } 
} 
class Maptest  
{ 
 public static void main(String[] args)  
 { 
  HashMap<Person,String> hm=new HashMap<Person,String>(); 
  hm.put(new Person("lsi1",35),"beijin"); 
  hm.put(new Person("lsi2",34),"sichuan"); 
  hm.put(new Person("lsi3",33),"gauangz"); 
  hm.put(new Person("lsi4",32),"tianjing"); 
  hm.put(new Person("lsi5",38),"jiling"); 
  hm.put(new Person("lsi5",38),"jiling"); 
  hm.put(new Person("lsi6",64),"cahgcun"); 
  //第一种取值方式Keyset 
  Set<Person> set=hm.keySet();//从hm中取出所有的键 
  for (Iterator<Person> it=set.iterator();it.hasNext() ; ) 
  { 
   Person p=it.next();//从it中获取键 
   String val=hm.get(p); 
   System.out.println(p+"----"+val); 
  } 
   
  System.out.println("========"); 
  //第二中取值方式 
  Set<Map.Entry<Person,String>> setmap=hm.entrySet();//获取映射中的映射关系 
  for (Iterator<Map.Entry<Person,String>> it=setmap.iterator();it.hasNext() ; ) 
  { 
   Map.Entry<Person,String> map=it.next(); 
   Person p=map.getKey(); 
   String addr=map.getValue(); 
   System.out.println(p+"---"+addr); 
  } 
 
 } 
} 
 
 |