TreeSet的排序之自然排序——compareTo
TreeSet会调用元素的compareTo(Objecto)方法来比较元素之间的大小关系,然后将集合里的元素按升序排列.此时需要排序元素的类必须实现Compareble接口,并覆写其int compareTo(Objecto)方法;
该方法用于比较对象,若:obj1,compareTo(obj2),返回0,表示两个对象相等,若返回一个正整数,表示obj1大于obj2,若返回一个负整数,表示obj1小于obj2;
对于TreeSet集合而言,判断两个对象相等的标准是:
compareTo()方法比较返回 0;
<span style="font-size:18px;">//TreeSet可以自动进行排序!最简单的情况
import java.util.*;
public class Demo {
publicstatic void main(String[] args) {
Set<Integer>s = new TreeSet<Integer>();
s.add(1);
s.add(192);
s.add(123);
System.out.println(s);//[1, 123, 192]
}
}
稍复杂点的
//TreeSet的自然排序,升序
import java.util.Set;
import java.util.TreeSet;
class Student implements Comparable{//必须实现接口
private Integer age;
public Student(Integer age) {
super();
this.age = age;
}
@Override
public int compareTo(Object o) {//比较的规则,运用泛型可以消除强转!
if(o instanceof Student){
Student s = (Student)o;
return this.age.compareTo(s.age);
}
return 0;
}
@Override
public String toString() {
return age+"" ;
}
}
public class Demo14 {
public static void main(String[] args) {
Set<Student> s = new TreeSet();
s.add(new Student(140));
s.add(new Student(15));
s.add(new Student(11));
s.add(new Student(63));
s.add(new Student(96));
System.out.println(s);//[11, 15, 63, 96, 140]
}
}</span>
TreeSet的排序之定制排序——Comparator
TreeSet的自然排序是根据元素的大小进行升序排序的,若想自己定制排序,比如降序排序,就可以使用Comparator接口了:
必须实现Comparator接口,并覆写其public intcompare(Object o1, Object o2)方法,该int compare(Object o1,Object o2)方法,用于比较两个对象的大小,比较结果和compareTo方法一致;
要实现定制排序,需要在创建TreeSet集合对象时,提供一个一个Comparator对象,该对象里负责集合元素的排序逻辑;
TreeSet(Comparator comparator)
<span style="font-size:18px;">//定制排序的话,必须在创建TreeSet集合对象的时候提供一个Comparator方法
import java.util.*;
class Student1{
private Integer age;
public Student1(Integer age) {
super();
this.age = age;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return age + "";
}
}
class MyComparator implements Comparator{
@Override
public int compare(Object o1, Object o2) {
if(o1 instanceof Student1 & o2 instanceof Student1){
Student1 s1 = (Student1)o1;
Student1 s2 = (Student1)o2;
if(s1.getAge() >s2.getAge()){
return -1;
}else if(s1.getAge() < s2.getAge()){
return 1;
}
}
return 0;
}
}
public class Demo {
public static void main(String[] args) {
Set<Student1> s = new TreeSet(new MyComparator());
/**
* 要实现定制排序,需要在创建TreeSet集合对象时,提供一个一个Comparator对象,
* 该对象里负责集合元素的排序逻辑;
*/
s.add(new Student1(140));
s.add(new Student1(15));
s.add(new Student1(11));
s.add(new Student1(63));
s.add(new Student1(96));
System.out.println(s);
}
}
</span>