JAVA小练习112——TreeSet的练习(2)


import java.util.Comparator;
import java.util.TreeSet;

class Emp implements Comparable<Emp> {

	String name;
	
	int age;
	
	double salary;

	public Emp(String name, int age, double salary) {
		this.name = name;
		this.age = age;
		this.salary = salary;
	}
	
	@Override
	public String toString() {
		return "{ 姓名:"+ this.name+" 年龄:"+ this.age+ " 薪水:"+this.salary+"}";
	}

	/*
	 * 元素与元素之间的比较规则定义在COmpareTo方法上。(non-Javadoc)
	 	返回值:负整数、零或正整数,根据此对象是小于、等于还是大于指定对象。 

	 */
	@Override  //  100.52 - 100.32 = 0.2
	public int compareTo(Emp e) {
		return (int)( this.salary-e.salary);
	}
}

//自定义一个比较器类
class AgeComparator implements Comparator<Emp>{

	@Override
	public int compare(Emp o1, Emp o2) {
		return o1.age-o2.age;
	}
}


public class Demo112 {

	public static void main(String[] args) {
		//创建一个比较器对象
		AgeComparator ageComparator = new AgeComparator();
		
		TreeSet tree = new TreeSet(ageComparator);
		tree.add(new Emp("家宝",68,200));
		tree.add(new Emp("永康",78,100));    
		tree.add(new Emp("习总",58,300));
		tree.add(new Emp("克强",48,500));
		
		System.out.println(tree);
	}
	
}

上一篇:Java集合——Set 接口、HashSet 实现类、TreeSet 实现类、LinkedHashSet 实现类


下一篇:Android字典TreeSet加载时间更快