TreeSet红黑树结构
- 存进去无序,但是取出来时会有排序(红黑树算法)
- 这个集合在SortedSet接口下
存储对象元素
对象就必须实现Comparable接口,和其下的compareTo方法
Student实体类
//实现Comparable接口并泛型
public class Student implements Comparable<Student>{
public String name;
public int age;
public char sex;
public Student(){}
public Student(String name,int age,char sex){
this.age = age;
this.name = name;
this.sex = sex;
}
实现compare()
如果对象的全部属性都相同,就代表是重复元素
@Override
public int compareTo(Student o) {
int name = this.name.compareTo(o.name);
int age = this.age - o.age;
int sex = this.sex - o.sex;
/**
* 两者的name属性数据相同,
* 判断其他属性数据是否相同
*/
return name == 0 ? age - sex : name;
}
main()
package com.li.changGe.collections.setGather;
import com.li.changGe.pojo.Student;
import java.util.Set;
import java.util.TreeSet;
public class TreeSetDemo01 {
public static void main(String[] args) {
Set<Student> set = new TreeSet();
Student student = new Student("长歌",18,'女');
Student student1 = new Student("世民",22,'男');
Student student2 = new Student("则天",20,'女');
set.add(student);
set.add(student1);
set.add(student2);
//----------------------------------------------------------------
//重写compareTo()后按照属性来判重
set.add(new Student("长歌",18,'女'));
//重写前长度4,重写后3
System.out.println("长度:"+set.size()+"\n"+set);
}
}