java集合 TreeMap 使用自然排序和定制排序

时间:2025-04-03 19:55:43
import ;
import ;

public class Demo3 {  
    public static void main(String[] args) 
    {  
    	("使用自然排序:");
    	TreeMap<IdNumber2, String> treeMap=new TreeMap<IdNumber2,String>();
    	(new IdNumber2(1000), "王尼玛");
    	(new IdNumber2(1001), "万尼玛");
    	(new IdNumber2(1002), "蓝尼玛");
    	(new IdNumber2(1003), "冯尼玛");
    	(new IdNumber2(1004), "秦尼玛");
    	("treeMap="+treeMap);
    	("使用定制排序:(从小到大排序)");
    	//使用钉子排序,指明比较器
    	TreeMap<IdNumber2, String> treeMap2=
    			new TreeMap<IdNumber2,String>(new MyComparatorBigToSmall());
    	(new IdNumber2(1000), "王尼玛");
    	(new IdNumber2(1001), "万尼玛");
    	(new IdNumber2(1002), "蓝尼玛");
    	(new IdNumber2(1003), "冯尼玛");
    	(new IdNumber2(1004), "秦尼玛");
    	("treeMap2="+treeMap2);
    	("使用定制排序:(从大到小排序)");
    	TreeMap<IdNumber2, String> treeMap3=
    			new TreeMap<IdNumber2,String>(new MyComparatorSmallToBig());
    	(new IdNumber2(1000), "王尼玛");
    	(new IdNumber2(1001), "万尼玛");
    	(new IdNumber2(1002), "蓝尼玛");
    	(new IdNumber2(1003), "冯尼玛");
    	(new IdNumber2(1004), "秦尼玛");
    	("treeMap2="+treeMap3);
    }  
}  
  //自定义比较器:实现comparator接口
class MyComparatorBigToSmall implements Comparator<IdNumber2> //使用泛型
{  
 
	@Override
	public int compare(IdNumber2 o1, IdNumber2 o2) {
		// TODO Auto-generated method stub
		return ()-();//从小到大排序
	}
} 
class MyComparatorSmallToBig implements Comparator<IdNumber2>
{
	@Override
	public int compare(IdNumber2 o1, IdNumber2 o2) {
		// TODO Auto-generated method stub
		return ()-();//从小到大排序
	}
}
//z作为键的类实现Comparable接口
class IdNumber2 implements Comparable<IdNumber2>
{
	//成员属性
	private int IdNumber;
	public int getIdNumber()
	{
		return IdNumber;
	}
	//构造函数
	public IdNumber2() {
		// TODO Auto-generated constructor stub
	}
	//构造函数
	public IdNumber2(int IdNumber)
	{
		=IdNumber;
	}
	//重写toString()方法
	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return "["++"]";
	}
	//重写equals()方法
	@Override
	public boolean equals(Object obj) 
	{
		if(obj==this)//自己和自己比较
			return true;//那就是同一个相等了
		//传入的引用不为空,而且两个的类型一样
		if(obj!=null&&()==())
		{
			IdNumber2 idNumber2=(IdNumber2) obj;//类型转换
			return ==;
			//如果两个的编号一样,那就认为相等
		}
		return false;
	}
	//重写hashCode()方法
	@Override
	public int hashCode() {
		// TODO Auto-generated method stub
		return *100;
	}
	//重写compareTo()方法实现自然排序
	@Override
	public int compareTo(IdNumber2 o) 
	{
		// TODO Auto-generated method stub
		//return ;//从小到大排序:
		return ;//从大到小排序
	}
}

相关文章