package TreeSet;
import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;
/*
* TreeSet是存放按自然顺序存放元素,同时是不允许重复的,在存放元素时,就会开始比较,看是否有重复了。
* 比较的方法:实现Comparable接口 或者Comparator接口
* Comparable接口:元素本身具备比较的特性
* Comparator接口:集合本身具备比较的特性
* */
public class TreeSet_2 {
public static void main(String[] args) {
Set t=new TreeSet<Emp>(new MyCompare());
Emp e1=new Emp(100);
Emp e2=new Emp(200);
Emp e3=new Emp(300);
Emp e4=new Emp(400);
t.add(e1);
t.add(e2);
t.add(e3);
t.add(e4);
for(Object o:t) {
System.out.println(o);
}
}
}
//定义一个比较器
class MyCompare implements Comparator<Emp>{
@Override
public int compare(Emp o1, Emp o2) {
// TODO Auto-generated method stub
return o1.getSalary()-o2.getSalary();
}
}
class Emp /*implements Comparable<Emp>*/{
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
private int salary;
public Emp() {
super();
// TODO Auto-generated constructor stub
}
public Emp(int salary) {
super();
this.salary = salary;
}
@Override
public String toString() {
return "Emp [salary=" + salary + "]";
}
/*@Override
public int compareTo(Emp o) {
// TODO Auto-generated method stub
return this.salary-o.salary;
}
*/
}
集合--treeSet
最新推荐文章于 2022-04-13 14:16:35 发布