树集 treeset是将输入的元素自然排序后存储,最后输出的顺序也是自然排序后的顺序
同时,元素不可重复;
import java.util.TreeSet;
public class treeset {
public static void main(String[] args) {
//存储整数
TreeSet<Integer> ts = new TreeSet<>(); //此时必须用Integer类
ts.add(1);//会自动装箱
ts.add(2);
ts.add(-12);
for (Integer i :ts){
System.out.println(i); //会根据自然排序输出,且是不重复的
// -12 1 2
}
}
}
实现compare接口后存储
public class Student implements Comparable<Student> {
String name ;
int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override // 重写compareto方法
public int compareTo(Student c){
/*return 0; //返回0 按照全部相同处理,返回 1 按照添加顺序
// 返回 -1 按照添加的逆序*/
int num = this.age - c.age ;//其中this是后一个输入的,c指代前一个输出的
int num2 = num ==0 ? this.name.compareTo(c.name) :num; //年龄相同的时候比较姓名
//注意,this.name 是一个字符串,因为comparator接口实现了String,所以可以直接调用它的方法;
return num2;
}
}
import java.util.TreeSet;
public class treeset {
public static void main(String[] args) {
//存储整数
TreeSet<Student> ts = new TreeSet<>(); //此时必须用Integer类
ts.add(new Student("a",10));//会自动装箱
ts.add(new Student("ab",12));
ts.add(new Student("abc",13));
for (Student i :ts){
System.out.println(i.getName()+i.getAge()); //会根据自然排序输出,且是不重复的
//由于排序规则里面返回值是0,故所有添加的元素最后在比较是都当成0,成为重复元素
//最后只能添加一个元素
}
}
}
比较器comparator的使用:
public class treeset {
public static void main(String[] args) {
//带参构造,传递的参数是一个比较器接口,以内部类的形式写入,并重写了compare方法
TreeSet<Student> ts = new TreeSet<>(
new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
int num = o1.getAge()- o2.getAge();
int num2 = num ==0 ? o1.getName().compareTo(o2.getName()):num;
return num2;
}
}); //此时必须用Integer类
ts.add(new Student("a",10));//会自动装箱
ts.add(new Student("ab",12));
ts.add(new Student("abc",13));
for (Student i :ts){
System.out.println(i.getName()+i.getAge()); //会根据自然排序输出,且是不重复的
}
}
}