import java.util.*;
class MapTest
{
public static void main(String[] args)
{
TreeMap<Student,String> map=new TreeMap<Student,String>(new MyCompara());
map.put(new Student("java01",26),"beijing");
map.put(new Student("java03",22),"nanjing");
map.put(new Student("java04",24),"haerbin");
map.put(new Student("java02",21),"hegang");
map.put(new Student("java05",20),"jiangbin");
map.put(new Student("java02",21),"hegang");
map.put(new Student("java05",20),"jiangbin");
Set<Map.Entry<Student,String>> entrySet=map.entrySet();
Iterator<Map.Entry<Student,String>> it=entrySet.iterator();
while(it.hasNext())
{
Map.Entry<Student,String> me=it.next();
Student stu=me.getKey();
String addr=me.getValue();
System.out.println(stu+":::"+addr);
}
}
}
class Student implements Comparable<Student>
{
private String name;
private int age;
public int compareTo(Student s)
{
int n=new Integer(this.age).compareTo(new Integer(s.age));
if(n==0)
{
return this.name.compareTo(s.name);
}
return n;
}
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;
}
Student(String name,int age)
{
this.name=name;
this.age=age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public String toString()//重写后解决 年龄输出为哈希值问题
{
return name+" "+age;
}
}
class MyCompara implements Comparator<Student>
{
public int compare(Student s1,Student s2)
{
int n=s1.getName().compareTo(s2.getName());
if(n==0)
{
return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
}
return n;
}
}
TreeSet 练习
最新推荐文章于 2021-07-16 22:27:19 发布