更新時(shí)間:2019-09-01 09:00:00 來源:動(dòng)力節(jié)點(diǎn) 瀏覽4046次
今天動(dòng)力節(jié)點(diǎn)java培訓(xùn)機(jī)構(gòu)小編為大家分享“Java中TreeSet的三種比較方法”,希望能夠幫助到大家,下面就隨小編一起看看Java中TreeSet的三種比較方法都是什么?
1、讓元素具備比較性
元素自身具備比較性,需要元素實(shí)現(xiàn)Comparable接口,重寫compareTo方法,也就是讓元素自身具備比較性,這種方式叫做元素的自然排序也就做默認(rèn)排序
// 第一種比較方法
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("不是學(xué)生對(duì)象");
Student s = (Student) o;
int differenceValue = this.age - s.age;
if(differenceValue == 0) return this.name.compareTo(s.name);
return differenceValue;
}
}
2、寫一個(gè)類來實(shí)現(xiàn)Comparator接口
當(dāng)元素自身不具備比較性,或者自身具備的比較性不是所需要的。那么此時(shí)可以讓容器自身具備。需要定義一個(gè)類實(shí)現(xiàn)接口Comparator,重寫compare方法,并將該接口的子類實(shí)例對(duì)象作為參數(shù)傳遞給TreeMap集合的構(gòu)造方法。
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
注意:當(dāng)Comparable比較方式和Comparator比較方式同時(shí)存在時(shí),以Comparator的比較方式為主;在重寫compareTo或者compare方法時(shí),必須要明確比較的主要條件相等時(shí)要比較次要條件,
3、第三種為匿名內(nèi)部類方法
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;
}
});
以上就是動(dòng)力節(jié)點(diǎn)java培訓(xùn)機(jī)構(gòu)小編介紹的“Java中TreeSet的三種比較方法”的內(nèi)容,希望通過此文能夠幫助到大家,如有疑問,請(qǐng)?jiān)诰€咨詢,有專業(yè)老師隨時(shí)為你服務(wù)。
相關(guān)免費(fèi)視頻教程推薦
java TreeSet特點(diǎn)視頻教程下載: http://www.soulsinkind.com/xiazai/2508.html
相關(guān)閱讀
Java實(shí)驗(yàn)班
0基礎(chǔ) 0學(xué)費(fèi) 15天面授
Java就業(yè)班
有基礎(chǔ) 直達(dá)就業(yè)
Java夜校直播班
業(yè)余時(shí)間 高薪轉(zhuǎn)行
Java在職加薪班
工作1~3年,加薪神器
Java架構(gòu)師班
工作3~5年,晉升架構(gòu)
提交申請(qǐng)后,顧問老師會(huì)電話與您溝通安排學(xué)習(xí)