存进去无序,但是取出来时会有排序(红黑树算法)这个集合在SortedSet接口下
存储对象元素
对象就必须实现Comparable接口,和其下的compareTo方法
Student实体类//实现Comparable接口并泛型 public class Student implements Comparable实现compare(){ 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; }
如果对象的全部属性都相同,就代表是重复元素
@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;
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 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);
}
}



