TReeSet
TReeSet底层使用了TreeMap实现,大家可以看一下JDK的源码,他的内部维持了一个简化版的TreeMap,通过key来存储Set的元素,TreeSet内部需要对存储的元素进行排序,因此我们对应的类需要实现Comparable接口,这样才能进行内部排序
TreeSet的应用(排序)
package com.boker.Collection;
import java.util.Set;
import java.util.TreeSet;
public class TestTreeSet {
public static void main(String[] args) {
Set<Integer> set = new TreeSet<>();
set.add(1);
set.add(4);
set.add(3);
set.add(2);
int count = 0;
//按照元素的递增方式排序
for(Integer m : set) {
System.out.print(m);
count++;
if(count>0 && count<4) {
System.out.print("<");
}else {
System.out.println();
}
}
Set<Car> set2 = new TreeSet<>();
set2.add(new Car("大众",230000,"黑色"));
set2.add(new Car("奥迪",400000,"白色"));
set2.add(new Car("别克",360000,"灰色"));
for(Car m : set2) {
System.out.println(m);
}
}
}
class Car implements Comparable<Car>{
private String brand;
private int price;
private String color;
//构造方法
public Car(String brand, int price, String color) {
this.brand = brand;
this.price = price;
this.color = color;
}
//Set和Get方法
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
@Override
public String toString() {
return this.brand + "," + this.price + "," + this.color;
}
@Override
public int compareTo(Car c) {
//比较价格
if(this.price > c.price) {
return 1;
}else if(this.price < c.price){
return -1;
}else {
//价格相等
return 0;
}
}
}
运行结果: