存入Integer类型数据(内部比较器)
TreeSet<Integer> tr = new TreeSet<>();
tr.add(12);
tr.add(16);
tr.add(45);
tr.add(19);
tr.add(14);
tr.add(16);
System.out.println(tr.size());
System.out.println(tr);
}
特点:唯一, 无序(没有按照输入顺序进行输出)有序(按照升序进行遍历)
原理:底层:二叉树(数组结构中的逻辑结构)
放入String类型(底层也是实现了内部比较器)
st.add("e");
st.add("a");
st.add("b");
st.add("d");
st.add("c");
st.add("e");
System.out.println(st.size());
System.out.println(st);
}
想放入自定义的Student类型的数据
利用内部比较器
public class Student implements Comparable<Student>{
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Student(int age, String name) {
this.age = age;
this.name = name;
}
@Override
public String toString() {
return "Student{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
@Override
public int compareTo(Student o) {
return this.getAge() - o.getAge();
}
}
通过外部比较器
class BiJiao implements Comparator<Student> {
@Override
public int compare(Student o1, Student o2) {
return o1.getName().compareTo(o2.getName());
}
}
public class Doem04 {
public static void main(String[] args) {
//利用外部比较器,必须自己制定
Comparator<Student> biJiao = new BiJiao();
TreeSet<Student> st = new TreeSet<>(biJiao);//一旦指定了外部比较器,那么就会按照外部比较器来比较
st.add(new Student(10,"clili"));
st.add(new Student(11,"blili"));
st.add(new Student(5,"alili"));
st.add(new Student(6,"clili"));
st.add(new Student(10,"dlili"));
st.add(new Student(17,"elili"));
System.out.println(st.size());
System.out.println(st);
}
实际应用中外部比较器多,运用了多态的写法
换一种写法
public static void main(String[] args) {
//利用外部比较器,必须自己制定
/* Comparator<Student> biJiao = new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.getName().compareTo(o2.getName());
}
};*/
TreeSet<Student> st = new TreeSet<>(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.getName().compareTo(o2.getName());
}
TreeSet是按照肾虚遍历出来的,二叉树