更新時間:2019-09-01 09:00:00 來源:動力節點 瀏覽3643次
今天動力節點java培訓機構小編為大家分享“Java中TreeSet的三種比較方法”,希望能夠幫助到大家,下面就隨小編一起看看Java中TreeSet的三種比較方法都是什么?
1、讓元素具備比較性
元素自身具備比較性,需要元素實現Comparable接口,重寫compareTo方法,也就是讓元素自身具備比較性,這種方式叫做元素的自然排序也就做默認排序
// 第一種比較方法
public class Student implements Comparable
//public class Student{
private String name;
private int age;
@Override
public int compareTo(Object o) {
if(!(o instanceof Student))
throw new RuntimeException("不是學生對象");
Student s = (Student) o;
int differenceValue = this.age - s.age;
if(differenceValue == 0) return this.name.compareTo(s.name);
return differenceValue;
}
}
2、寫一個類來實現Comparator接口
當元素自身不具備比較性,或者自身具備的比較性不是所需要的。那么此時可以讓容器自身具備。需要定義一個類實現接口Comparator,重寫compare方法,并將該接口的子類實例對象作為參數傳遞給TreeMap集合的構造方法。
import java.util.Comparator;
// 第二種比較方法
public class ComparatorLean implements Comparator
@Override
public int compare(Object o1, Object o2) {
Student s1 = (Student) o1;
Student s2 = (Student) o2;
int differenceValue = this.age - s.age;
if(differenceValue == 0) return new Integer(s1.getName().compareTo(s2.getName()));
return differenceValue;
}
}
TreeSet
注意:當Comparable比較方式和Comparator比較方式同時存在時,以Comparator的比較方式為主;在重寫compareTo或者compare方法時,必須要明確比較的主要條件相等時要比較次要條件,
3、第三種為匿名內部類方法
TreeSet
@Override
public int compare(Object o1, Object o2) {
Student s1 = (Student) o1;
Student s2 = (Student) o2;
int num = s1.getAge() - s2.getAge();
if(num==0) return s1.getAge() - s2.getAge();
return num;
}
});
以上就是動力節點java培訓機構小編介紹的“Java中TreeSet的三種比較方法”的內容,希望通過此文能夠幫助到大家,如有疑問,請在線咨詢,有專業老師隨時為你服務。
相關免費視頻教程推薦
java TreeSet特點視頻教程下載: http://m.dabaquan.cn/xiazai/2508.html
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習