TreeSet和自然排序定制排序
Treeset是一个有序的集合,它的作用是提供有序的Set集合,可以按照添加对象的属性进行排序。
注意: 向TreeSet中添加数据时,要求数据时相同类的对象。
自然排序(实现Comparable接口):自然排序中,比较两个对象相同的方法时compareTo,如果一样返回0。
整数类型:
package com.cheng.collection;
import org.junit.Test;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
public class TreeSetTest {
String类型:
package com.cheng.collection;
import org.junit.Test;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
public class TreeSetTest {
Person类:
Person类重写compareTo方法:
package com.cheng.collection;
import java.util.Objects;
public class Person implements Comparable{//此处实现Comparable接口
private String name;
private int age;
public Person() {
}
public Person(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;
}
//按照姓名升序排序,此时有两个姓名一样但年龄不同的person
定制排序:

浙公网安备 33010602011771号