總結TreeSet排序問題

java中接口Set有衆多實現類,而HashSet和TreeSet是最常用的兩個,這裏總結TreeSet實現排序的2種方式:

1.通過TreeSet(Comparator<? super E> comparator) 構造方法指定TreeSet的比較器進行排序;

2.使用TreeSet()構造方法,並對需要添加到set集合中的元素實現Comparable接口進行排序;

 

1.通過TreeSet(Comparator<? super E> comparator) 構造方法指定TreeSet的比較器進行排序;

(1).構造裝入TreeSet的java bean

例如:

package src;

public class Foo {
 private int num;
 public int getNum() {
  return num;
 }
 public void setNum(int num) {
  this.num = num;
 }
 
 public String toString()
 {
  return "foo:" + this.getNum() + ",";
 }
}


 

(2).自己實現比較器

例如:


package src;
import java.util.Comparator;
public class MyComparator implements Comparator<Foo> {
 public int compare(Foo f1,Foo f2) {
  
  if (f1.getNum() > f2.getNum())
  {
   return 1;
  }
  else if (f1.getNum() == f2.getNum())
  {
   return 0;
  }
  else
  {
   return -1;
  }
 }
}


 

(3)new TreeSet時指定比較器

TreeSet<Foo> set = new TreeSet(new MyComparator());

這樣在set.add()元素時就會根據自己定義比較器進行排序了

 

2.使用TreeSet()構造方法,並對需要添加到set集合中的元素實現Comparable接口進行排序;

這種方法不需要自己寫一個比較器,需要對裝入set集合中的元素實現Comparable接口,TreeSet集合就根據bean的自然順序進行排序

(1).構造bean,需要實現Comparable接口,並重寫compareTo()方法,compareTo方法中定義排序的方式

例如:

package src;
public class Foo implements Comparable{
 private int num;
 public int getNum() {
  return num;
 }
 public void setNum(int num) {
  this.num = num;
 }
 
 public String toString()
 {
  return "foo:" + this.getNum() + ",";
 }
 public int compareTo(Object obj) {
  if (obj instanceof Foo)
  {
   Foo foo = (Foo)obj;
   if (this.num > foo.getNum())
   {
    return 1;
   }
   else if (this.num == foo.getNum())
   {
    return 0;
   }
   else
   {
    return -1;
   }
    
  }
  return 0;
 }
}


(2).創建TreeSet時直接使用構造TreeSet()方法

TreeSet<Foo> set = new TreeSet();

不需要指定比較器,這樣在執行set.add()方法時,set集合就自動根據bean中compareTo()方法指定的方式進行排序。

 

總結:2種方法任選其一都能達到目的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章