TreeSet底层实际是用TreeMap实现的,内部维持一个简化版本的TreeMap,通过key来存储Set元素。
TreeSet内部需要对存储的元素进行排序,因此,我们对应的类需要实现Comparable接口。
这样才能根据compareTo()方法进行比较对象的大小,才能进行内部排序
import java.util.Set;
import java.util.TreeSet;
public class TreeSetTest {
public static void main(String[] args) {
Set set = new TreeSet<>();
set.add(300);
set.add(200);
set.add(600);
//按照元素递增的方式排好序
for(Integer m:set){
System.out.println(m);
}
Set set2 = new TreeSet<>();
set2.add(new Emp2(100,"张三",3000));
set2.add(new Emp2(50,"李四",2000));
set2.add(new Emp2(150,"王五",8000));
set2.add(new Emp2(30,"赵六",20000));
for(Emp2 m:set2){
System.out.println(m);
}
}
}
class Emp2 implements Comparable {
int id;
String name;
double salary;
public Emp2(int id, String name, double salary) {
super();
this.id = id;
this.name = name;
this.salary = salary;
}
@Override
public String toString() {
return "id:"+id+",name:"+name+",salary:"+salary;
}
@Override
//负数:小于,0:等于,正数:大于
public int compareTo(Emp2 o) {
if(this.salary>o.salary){
return 1;
}else if(this.salary
return -1;
}else{
if(this.id>o.id){
return 1;
}else if(this.id
return -1;
}else{
return 0;
}
}
}
}
输出:
200
300
600
id:50,name:李四,salary:2000.0
id:100,name:张三,salary:3000.0
id:150,name:王五,salary:8000.0
id:30,name:赵六,salary:20000.0
Process finished with exit code 0