java set TreeSet詳解

來源:互聯網
上載者:User

標籤:範圍   package   col   strong   最大的   obj   rgs   不包含   fir   

TreeSet 是sortedSet的唯一實作類別,正如SortedSet名字暗示,TreeSet可以讓集合元素處在排好序的狀態。

與HashSet相比,TreeSet還額外提供了以下的方法(列出來,混個臉熟:)

SortedSet subSet(Object  fromElement,Object toElement) :返回這個Set的子集合,範圍從fromElement(包含)到toElement(不包含)

SortedSet headSet(Object toElement):返回這個Set的子集合,範圍小於toElement的子集合 

SortedSet tailSet(Object fromElement):返回這個Set的子集合,範圍大於或等於fromElement的子集合 

Object first(): 返回這個Set第一個元素 

Object last():返回這個Set最後一個元素

Object lower(Object e):返回小於指定元素的集合裡最大的那個元素 

Object higher(Object e):返回大於指定元素的集合裡最小的那個元素     

【以上參考元素都不需要是集合裡的

 總結一下,最後四個方法就是找到集合裡的第一個,前一個,後一個,最後一個元素。同時前三個就是返回該集合的合格子集合。

package Test01;import java.util.TreeSet;public class TestTreeSet {       public static void main(String[] args) {    TreeSet num =new TreeSet();    num.add(2);    num.add(-2);    num.add(10);    num.add(9);    System.out.println(num);   //看出:不是按照添加的順序來,是數字由小到大排序    System.out.println(num.first());  //看出:數字由小到大排序的第一個    System.out.println("9到12 之間的"+num.subSet(9, 12));    System.out.println("比8小的"+num.headSet(8));    System.out.println("比8大的"+num.tailSet(8));}}

 

與hashset採用hash演算法決定元素的儲存位置,TreeSet採用紅/黑樹狀結構的資料結構(待跟進)來儲存集合元素。那麼他的定序是怎麼的呢?

自然排序(預設情況)。

定製排序。

待續。。。。 

java set TreeSet詳解

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.