集合之TreeSet
集合之TreeSet
基本用法
以下代码使用TreeSet来存储数据:
package com.javalearn.map.treemap;
import java.util.TreeSet;
public class TestForTree {
public static void main(String[] args) {
TreeSet<String> ts = new TreeSet<>();
ts.add("cxf");
ts.add("asmf");
for (String s:ts) {
System.out.println(s); // 按首字母顺序升序
}
}
}
输出结果:
asmf
cxf
自定义比较
若TreeSet存放自定义的类对象,则需要自定义比较规则,代码如下:
package com.javalearn.map.treemap;
import java.util.TreeSet;
public class TestForTree {
public static void main(String[] args) {
TreeSet<Customer> ts = new TreeSet<>();
Customer c1 = new Customer(54);
Customer c2 = new Customer(23);
ts.add(c1);
ts.add(c2); // 存储时就会排序
for (Customer s:ts) {
System.out.println(s); // 按顺序打印
}
}
}
class Customer implements Comparable<Customer> { // 实现comparable接口才能自定义比较规则
int age;
public Customer(int age) {
this.age = age;
}
@Override
public int compareTo(Customer o) { // 制定比较规则,大于0、等于0或者小于0,底层大于0则往右子树找,等于0则覆盖,小于0则往左子树找。this和o比较
return this.age - o.age;
}
@Override
public String toString() {
return "Customer{" +
"age=" + age +
'}';
}
}
输出结果:
Customer{age=23}
Customer{age=54}
实现比较器接口
除了用被存储的元素实现Comparable,还可以直接实现比较器接口Comparator,代码如下:
package com.javalearn.map.compare;
import java.util.Comparator;
import java.util.TreeSet;
public class TestForCompare {
public static void main(String[] args) {
Animal animal = new Animal(32);
Animal animal1 = new Animal(66);
TreeSet<Animal> treeSet = new TreeSet<>(new MyCompare()); // 此处需要传入比较器,否则把key向上转为Comparable,作为默认比较器
treeSet.add(animal);
treeSet.add(animal1);
for (Animal a:treeSet) {
System.out.println(a);
}
System.out.println();
TreeSet<Animal> treeSet1 = new TreeSet<>(new Comparator<Animal>() { // 匿名内部类,实现比较器
@Override
public int compare(Animal o1, Animal o2) {
return o1.age- o2.age;
}
});
treeSet1.add(animal);
treeSet1.add(animal1);
for (Animal a:treeSet) {
System.out.println(a);
}
}
}
class Animal {
int age;
public Animal(int age) {
this.age = age;
}
@Override
public String toString() {
return "Animal{" +
"age=" + age +
'}';
}
}
class MyCompare implements Comparator<Animal> { // new TreeSet时需传入的比较器
@Override
public int compare(Animal o1, Animal o2) {
return o1.age- o2.age;
}
}
输出结果:
Animal{age=32}
Animal{age=66}
Animal{age=32}
Animal{age=66}