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

【java编程】Map集合之TreeMap按学生姓名进行升序排序

2015-02-26 09:52 826 查看
import java.util.*;
/*要对键值对进行排序,只能用TreeMap来排序
HashMap底层是哈希表,哈希表是随机的*/
class TreeMapDemo
{
public static void main(String[] args)
{
TreeMap<Student,String> tm = new TreeMap<Student,String>(new compl());
tm.put(new Student("wc",24),"shanghai");
tm.put(new Student("wa",26),"xinjiang");
tm.put(new Student("wb",25),"hubei");
tm.put(new Student("wd",28),"hunan");
Set<Map.Entry<Student,String>> entrySet=tm.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.getName()+":"+stu.getAge()+"-----"+addr);
}
}
}

//自建比较器实现按姓名排序
class compl implements Comparator<Student>
{
public int compare(Student s1,Student s2)
{
int num=s1.getName().compareTo(s2.getName());
if(num==0)
return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
return num;
}
}

class Student implements Comparable<Student>//实现Comparable方法让Student具备比较性
{
private String name;
private int age;
Student(String name,int age)
{
this.name=name;
this.age=age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
//复写hashCode方法为哈希表判断重复元素使用
public int hashCode()
{
return this.name.hashCode()+age*20;
}
//复写equals方法
public boolean equals(Object obj)
{
if(!(obj instanceof Student))
throw new ClassCastException("类型不匹配!");
Student s=(Student)obj;
return this.name.equals(s.getName()) && this.age==s.getAge();
}
//复写compareTo方法
public int compareTo(Student s)
{
int num=new Integer(this.age).compareTo(new Integer(s.getAge()));
if(num==0)
return this.name.compareTo(s.getName());
return num;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐