當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java ConcurrentSkipListSet subSet()用法及代碼示例


java.util.concurrent.ConcurrentSkipListSet的subSet()方法是Java中的內置函數,其中元素在此方法定義的範圍內返回。該函數的語法使您可以清楚地了解指定元素,並附帶示例。

用法:

subSet(E fromElement, E toElement)
           or 
subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive)

參數:
此方法的第一個變體采用兩個參數,這些參數定義了將要返回的元素的範圍。 toElement不包含在返回的集中。


第二個變體與第一個變體相似,但此處的布爾參數專門包含或排除了toElement和fromElement。
返回:
第一個方法變體返回此集合部分的視圖,其元素範圍從fromElement(包括)到toElement(不包括)。
第二種方法變體返回此集合部分的視圖,該元素的範圍從boolean inclusive參數定義的fromElement到toElements。

異常:
NullPointerException :如果指定的元素為NULL。

下麵是示例程序,用於說明Java中的ConcurrentSkipListSet subSet():

範例:1

返回從30000到90000的元素,但排除90000。

// Java program to demonstrate ConcurrentSkipListSet subSet() method 
  
import java.util.concurrent.ConcurrentSkipListSet; 
  
class ConcurrentSkipListSetExample { 
    public static void main(String[] args) 
    { 
  
        // Initializing the set using ConcurrentSkipListSet() 
        ConcurrentSkipListSet<Integer> 
            set = new ConcurrentSkipListSet<Integer>(); 
  
        // Adding elements to this set 
        set.add(65552); 
        set.add(34324); 
        set.add(93423); 
        set.add(41523); 
        set.add(90000); 
  
        // Printing the ConcurrentSkipListSet 
        System.out.println("ConcurrentSkipListSet:"
                           + set); 
  
        // Printing the elements of ConcurrentSkipListSet that 
        // are retured by subSet() method 
        System.out.println("The returned elements are:"
                           + set.subSet(30000, 90000)); 
    } 
}
輸出:
ConcurrentSkipListSet:[34324, 41523, 65552, 90000, 93423]
The returned elements are:[34324, 41523, 65552]

示例:2
在此示例中,還返回了元素400,因為布爾值包含為true。

// Java program to demonstrate ConcurrentSkipListSet subSet() method 
  
import java.util.concurrent.ConcurrentSkipListSet; 
  
class ConcurrentSkipListSetExample { 
    public static void main(String[] args) 
    { 
  
        // Initializing the set using ConcurrentSkipListSet() 
        ConcurrentSkipListSet<Integer> 
            set = new ConcurrentSkipListSet<Integer>(); 
  
        // Adding elements to this set 
        set.add(652); 
        set.add(324); 
        set.add(400); 
        set.add(123); 
        set.add(200); 
  
        // Printing the ConcurrentSkipListSet 
        System.out.println("ConcurrentSkipListSet:"
                           + set); 
  
        // Printing the elements of ConcurrentSkipListSet that 
        // are retured by subSet() method 
        System.out.println("The returned elements are:"
                           + set.subSet(100, true, 400, true)); 
    } 
}
輸出:
ConcurrentSkipListSet:[123, 200, 324, 400, 652]
The returned elements are:[123, 200, 324, 400]


相關用法


注:本文由純淨天空篩選整理自ProgrammerAnvesh大神的英文原創作品 ConcurrentSkipListSet subSet() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。