import java.util.*;
class circle{
public static void main(String [] agrs)
{
HashMap<student,String> t = new HashMap<student,String>();
t.put(new student("key01",21),"look");
t.put(new student("key02",25),"university");
t.put(new student("key03",23),"open");
t.put(new student("key04",24),"person");
Set<Map.Entry<student, String>> entrySet=t.entrySet();//将map中所有的键存入到set集合。
Iterator<Map.Entry<student,String>> it = entrySet.iterator();
while(it.hasNext())
{
Map.Entry<student, String> m =it.next();
student stu=m.getKey();
String s=m.getValue();
System.out.println(stu+".."+s);
}
}
}
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;
/*
* new Integer(this.age)的意义就是把age转换为int类型的。*/
}
public int hashCode()
{
return name.hashCode()+age;
}
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;
}
}
|
|