TreeMap的使用

Hello World

Posted by BY 人间喜剧 on November 4, 2019

TreeMap的排序问题:

记住在这里用了Comparable接口才能让对象做比较。

import java.util.Map;
import java.util.TreeMap;

/**
 * 测试TreeMap的使用
 * @author 13377
 *
 */
public class TestTreeMap {
public static void main(String[] args) {
	Map<Integer,String>treeMap=new TreeMap<>();
	treeMap.put(1,"aa");
	treeMap.put(5,"bb");
	treeMap.put(3,"cc");
	
	//按照key自增的方式排序。
	for (Integer key :treeMap.keySet()) {
		System.out.println(key+"------"+treeMap.get(key));
	}
	
	Map<Emp,String> treeMap2=new TreeMap<>();
	treeMap2.put(new Emp(1001,"杨人赞",500000),"杨赞是个好小伙");
	treeMap2.put(new Emp(1050,"张雪妹",600200),"张雪妹是个好小伙");
	treeMap2.put(new Emp(1030,"张雪",51000),"张雪是个好小伙");
	
	//按照key自增的方式排序。
		for (Emp key :treeMap2.keySet()) {
			System.out.println(key+"------"+treeMap2.get(key));
		}
}
}
class Emp implements Comparable<Emp>{
	int id;
	String name;
	int salay;
	public Emp(int id, String name, int salay) {
		super();
		this.id = id;
		this.name = name;
		this.salay = salay;
	}
	@Override
	public String toString() {
		return "id:"+id+",name:"+name+",salay:"+salay;
	}
	@Override
	public int compareTo(Emp arg0) {
		if (this.salay>arg0.salay) {
			return 1;
		}else if (this.salay<arg0.salay) {
			return -1;
		}if (this.id>arg0.id) {
			return 1;
		}else if (this.id<arg0.id) {
			return -1;
		}else {
			return 0;
		}
	}
	
}