您的位置:首页 > 编程语言 > Java开发

java基础入门----TreeMap练习1

2013-10-03 09:41 239 查看
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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: