国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

TreeSet的定制排序

2019-11-06 06:14:02
字體:
來源:轉載
供稿:網友

方式1:在元素自身中定義排序規則

需要元素自身實現Comparable接口

/*** *TreeSet是一個有序集合,TreeSet中元素將按照升序排列,缺省是按照 自然順序進行排列,意味著TreeSet中元素要實現Comparable接口。 我們可以在構造TreeSet對象時,傳遞實現了Comparator接口的比較器對象。 注意排序時:當主要的條件相同時,判斷次要條件。 * @author Administrator * */public class TreeSetTest { public static void main(String[] args) { TreeSet treeset = new TreeSet();//定義一個集合 treeset.add(new person2(10, "liuyia")); treeset.add(new person2(10, "liuyib")); treeset.add(new person2(15, "liuyi34")); treeset.add(new person2(11, "liuyi4")); treeset.add(new person2(12, "liuyi4")); Iterator itera = treeset.iterator(); while (itera.hasNext()) { System.out.PRintln(itera.next()); } }}class person2 implements Comparable {//實現Comparable 接口 private int age; private String name; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public person2(int age, String name) { this.age = age; this.name = name; } public int compareTo(Object o) { if(!(o instanceof person2)) throw new RuntimeException("對象類型不一致!"); person2 p = (person2)o; if(this.age>p.age){ return -1; } if(this.age<p.age){ return 1; } if(this.age==p.age){ return this.name.compareTo(p.name);//當主要的條件也就是age的值相同時時候此時判斷次要條件姓名 } return -1; } //打印結果 public String toString(){ return age+" = "+"name"+name; }}

方式2(傳給集合一個自定義排序器)

寫個實現Comparble接口的排序器

public class TreeSetTest { public static void main(String[] args) { //定義一個集合,并將自定義的排序器傳給集合。這樣該集合就會使用我們定義的排序規則來排序 TreeSet treeset = new TreeSet( new mycomp()); treeset.add(new person2(10, "liuyia")); treeset.add(new person2(10, "liuyib")); treeset.add(new person2(15, "liuyi34")); treeset.add(new person2(11, "liuyi4")); treeset.add(new person2(12, "liuyi4")); Iterator itera = treeset.iterator(); while (itera.hasNext()) { System.out.println(itera.next()); } }}class person2 { private int age; private String name; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public person2(int age, String name) { this.age = age; this.name = name; } public String toString(){ return age+" = "+"name"+name; }}class mycomp implements Comparator{ public int compare(Object o1, Object o2) { person2 p1 = (person2)o1; person2 p2 = (person2)o2; return -(p1.getAge()- p2.getAge()); }}
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 阿巴嘎旗| 防城港市| 蒙城县| 淮滨县| 阳江市| 阿克陶县| 南华县| 烟台市| 张家川| 炎陵县| 永胜县| 叙永县| 和政县| 尼勒克县| 迭部县| 蒙自县| 白山市| 肇东市| 尤溪县| 兴海县| 吉安县| 崇左市| 华亭县| 黑龙江省| 贵阳市| 加查县| 永宁县| 玛纳斯县| 睢宁县| 阿坝| 舞阳县| 定结县| 湖州市| 石棉县| 镇沅| 中江县| 淳化县| 宽甸| 同德县| 昌都县| 长沙市|