TreeMap实例

package com.zyf.day16;

import java.util.Comparator;
import java.util.TreeMap;

class Emp {//implements Comparable{
	String name;
	int salary;
	public Emp(String name, int salary) {
		super();
		this.name = name;
		this.salary = salary;
	}
	
/*	@Override
	public int compareTo(Emp o) {
		// TODO Auto-generated method stub
		return this.salary - o.salary;
	}*/
	
}
//
class MyComparator implements Comparator{

	@Override
	public int compare(Emp o1, Emp o2) {
		// TODO Auto-generated method stub
		return o1.salary - o2.salary;
	}
	
}
public class demo4 {
    public static void main(String[] args){
    	//创建一个自定义比较器
    	MyComparator comparator = new MyComparator();
    	
    	TreeMap tree = new TreeMap(comparator);
    	tree.put(new Emp("电动",2000),"001");
    	tree.put(new Emp("王五",4000),"002");
    	tree.put(new Emp("天天",7000),"003");
    	tree.put(new Emp("事实",29000),"004");
    	tree.put(new Emp("哦哦",29000),"009");
    	System.out.println(tree);
    	
    }
}


 
 

你可能感兴趣的:(java)