TreeMap的用法

TreeMap是一种Map,只是对其进行了排序,每一个TreeMap都有一一对应的key--value  ,其中,将key群补封装在一起,就构成了一个treeset下面通过一个程序说说TreeMap中的函数

<span style="font-size:14px;">import java.util.TreeMap;

public class Lel implements Comparable<Object> {

	int count;
	 Lel(int count){
		this.count = count;
	}
	public int compareTo(Object object) {
		// TODO Auto-generated method stub
		Lel lel = (Lel)object;
		if(lel.count ==this.count){
			return 0;
		}
		if(lel.count>this.count){
		return 1;
	}
		else {
			return -1;
		}
	}
	public String toString(){
		return "Lel(count属性:"+count+")";
	}
	public boolean equals(Object objObject){
		if(this==objObject){
			return true;
		}
		else if(objObject!=null&&objObject.getClass()==Lel.class){
			Lel lel = (Lel)objObject;
			if(lel.count==this.count){
				return true;
			}
		}
		return false;
		
	}
	public static class treeMap{
		public static void main(String []args){
		TreeMap treeMap =   new TreeMap<>();
		treeMap.put(new Lel(1),"嘿嘿,对不对");
		treeMap.put(new Lel(5),"下午上完课干嘛呢");
		treeMap.put(new Lel(3), "晚上想看看android");
		treeMap.put(new Lel(-1), "明天是星期五");
		System.out.println(treeMap.firstEntry());//返回第最大键值对
		System.out.println(treeMap.firstKey());//返回最大键key
		System.out.println(treeMap.lastEntry());//返回最小键值对
		System.out.println(treeMap.lastKey());//返回最小键
		System.out.println(treeMap.higherEntry(new Lel(3)));//返回3键值后面的键值对
		System.out.println(treeMap.higherKey(new Lel(3)));//返回键值3后面的键值
		System.out.println(treeMap.lowerEntry(new Lel(3)));    //返回上一个键值对
		System.out.println(treeMap.lowerKey(new Lel(3)));//返回上一个key
		System.out.println(treeMap.subMap(new Lel(3), new Lel(1)));//返回键值从3到1 的子map
		System.out.println(treeMap.subMap(new Lel(3), true, new Lel(1), true));//这个和上面一样,只是看是否包括
		System.out.println(treeMap.tailMap(new Lel(1)));//返回比你选择的key小的键值对
		System.out.println(treeMap.tailMap(new Lel(1), true));
		System.out.println(treeMap.headMap(new Lel(-1)));//返回比你选择的key大的键值对,不包括本身
		System.out.println(treeMap.headMap(new Lel(-1), true));//返回比你选择的key大的键值对
		
	}
}
</span>




猜你喜欢

转载自blog.csdn.net/u012223173/article/details/46359321