總結TreeSet排序問題__bean

來源:互聯網
上載者:User

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種方法任選其一都能達到目的。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.