需要元素自身實現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; }}寫個實現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()); }}新聞熱點
疑難解答