TreeSet中的元素总是处于有序的状态,在遍历时需要指明排序方式
其判断元素是否相同不再是根据equals()方法。
自然排序
一、需要继承comparable接口
例
储存的是User对象
需要User继承接口
二、重写compareTo方法
指明排序方式
①根据什么属性来排序
②升序还是降序
升序:直接返回结果
降序:返回值前加负号
定制排序
在需要在括号里传进一个参数,参数规定了排序的方式
代码如下:
User类
public class User implements Comparable {
private String name;
private int age;
public User() {
}
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public int compareTo(Object o) {
if(o instanceof User){
User user =(User) o;
// return this.name.compareTo(user.name);
int i=this.name.compareTo(user.name);
if(i!=0){
return i;
}else{
return Integer.compare(this.age,user.age);
}
}else{
throw new RuntimeException("输入的类型不匹配");
}
}
}
测试类
import org.junit.Test;
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;
public class TreeSetTest {
public static void main(String[] args) {
TreeSet set = new TreeSet();
set.add(new User("Frank",56));
set.add(new User("Durant",21));
set.add(new User("Jane",9));
set.add(new User("Alex",45));
set.add(new User("Sam",93));
set.add(new User("Sam",83));
Iterator iterator = set.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
}
@Test
public void test1(){
Comparator com=new Comparator() {
@Override
public int compare(Object o1, Object o2) {
if(o1 instanceof User&& o2 instanceof User){
User u1=(User) o1;
User u2=(User) o2;
return Integer.compare(u1.getAge(),u2.getAge());
}else {
throw new RuntimeException("输入的类型不匹配");
}
}
};
TreeSet set=new TreeSet(com);
set.add(new User("Frank",56));
set.add(new User("Durant",21));
set.add(new User("Jane",9));
set.add(new User("Alex",45));
set.add(new User("Sam",93));
set.add(new User("Sam",83));
Iterator iterator = set.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
}
}