import java.util.*;
import org.apache.catalina.tribes.group.interceptors.TwoPhaseCommitInterceptor.MapEntry;
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 = this.name.compareTo(s.name);
if(num==0)
{
return this.age-s.age;
}
return num;
}
public int hashCode()
{
//System.out.println(this.name+"^^hashCode^^"+this.age);
return name.hashCode()+age*34;
}
public boolean equals(Object obj)
{
if(!(obj instanceof Student))
throw new ClassCastException("类型不匹配");
Student s = (Student)obj;
System.out.println(this.name+"^^^^equals^^^"+s.name);
return this.name.equals(s.name)&&this.age==s.age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public String toString()
{
return this.getName()+":"+this.getAge();
}
}
public class MapTest
{
public static void main(String[] arge)
{
HashMap<Student,String> hm = new HashMap<Student,String>();
hm.put(new Student("wangwu2",23),"beijing");
hm.put(new Student("wangwu1",24),"shanghai");
hm.put(new Student("wangwu9",26),"xian");
hm.put(new Student("wangwu8",28),"nanjing");
Iterator<Student> it = hm.keySet().iterator();
Set<Map.Entry<Student, String>> s = hm.entrySet();
for(Map.Entry<Student, String> m:s)
{
Student key = m.getKey();
String value = m.getValue();
System.out.println(key + " " + value);
}
System.out.println("----------------------");
while(it.hasNext())
{
Student stu = it.next();
String value = hm.get(stu);
System.out.println(stu + " " + value);
}
}
}
迭代map集合的两种方式注意了,我给你都写出来了,再针对自己的代码再看看。 |