import java.util.*;
class TreeMap练习1
{
public static void sop(Object obj)
{
System.out.println(obj);
}
public static void main(String[] args)
{
TreeMap<Student0,String> hm = new TreeMap<Student0,String>(new StuNameComparator());
hm.put(new Student0("aaa",20),"nanjing");
hm.put(new Student0("bbb",24),"tianjing");
hm.put(new Student0("ccc",12),"beijing");
hm.put(new Student0("ccc",22),"beijing");
hm.put(new Student0("ass",20),"jingdong");
//第二种取出方式
Set<Map.Entry<Student0, String>> entrySet = hm.entrySet();
Iterator<Map.Entry<Student0, String>> iter = entrySet.iterator();
while(iter.hasNext())
{
Map.Entry<Student0, String> me = iter.next();
Student0 stu = me.getKey();
String address = me.getValue();
sop(stu+"......"+address);
}
}
}
class Student0 implements Comparable<Student0>
{
private String name;
private int age;
Student0(String name,int age)
{
this.name = name;
this.age = age;
}
public int hashCode()
{
return name.hashCode()+age*34;
}
public boolean equals(Object obj)
{
if(!(obj instanceof Student0))
throw new ClassCastException("类型不匹配");
Student0 s = (Student0)obj;
return this.name == s.name && this.age == s.age;
}
public int compareTo(Student0 s)
{
int num = new Integer(this.age).compareTo(new Integer(s.age));
if(num == 0)
return this.name.compareTo(s.name);
return num;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public String toString() //自定义学生类的输出方式,不然就 集合.Student0@17ae9.
{
return name+"==="+age;
}
}
class StuNameComparator implements Comparator<Student0>
{
public int compare(Student0 s1,Student0 s2)
{
int num = s1.getName().compareTo(s2.getName());
if(num==0)
return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
return num;
}
}
java基础入门----TreeMap练习1
最新推荐文章于 2023-09-10 12:31:11 发布