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

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;
	}
	
}

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值