Java TreeSet subSet() 方法

2024年11月7日 | 5 分钟阅读

TreeSet 类的 subSet() 方法用于获取范围在 fromElement 和 toElement 之间的集合元素。

语法

参数

fromElement - 返回集合的最小端点

toElement - 返回集合的最大端点。

返回

它返回范围在 fromElement 和 toElement 之间的集合。

抛出

ClassCastException:当 fromElement 和 toElement 的范围无法与集合中存在的元素进行比较时,抛出异常。

NullPointerException:当 fromElement 或 toElement 为 null 时,抛出异常。

IllegalArgumentException:当 fromElement 大于 toElement 或超出范围时,抛出异常。

示例 1

输出

TreeSet: [4, 6, 9, 12, 18]
Elements of  TreeSet: [6, 9]

示例 2

输出

TreeSet: [1, 3, 6, 9, A, B, a, b]
Elements of  TreeSet: [3, 6, 9, A, B]

示例 3

输出

Elements in TreeSet: 
1  Shristee  III B.tech(C.S)
2  Shweta    I   B.tech(I.t)
3  Suma      II  Msc(I.t)
4  Dolly     V   MCA
Elements of  TreeSet: [2  Shweta    I   B.tech(I.t), 3  Suma      II  Msc(I.t)]

Java TreeSet subSet() 方法

TreeSet 类的 subSet() 方法用于获取集合中范围在 fromElement 和 toElement 之间的元素。如果 fromElement 和 toElement 相等,并且 fromInclusive 和 toInclusive 都为 true,则返回 null 集。

语法

参数

fromElement - 返回集合的最小端点

fromInclusive - 如果最小端点要包含在返回的视图中,则为 true

toElement - 返回集合的最大端点。

toInclusive - 如果最大端点要包含在返回的视图中,则为 true

返回

它返回范围在 fromElement 和 toElement 之间的集合。

抛出

ClassCastException:当 fromElement 和 toElement 的范围无法与集合中存在的元素进行比较时,抛出异常。

NullPointerException:当 fromElement 或 toElement 为 null 时,抛出异常。

IllegalArgumentException:当 fromElement 大于或等于 toElement 且超出范围时,抛出异常。

示例 1

输出

TreeSet: [2, 3, 4, 6, 9, 12, 13, 16, 18, 25]
Elements in TreeSet object 1[4, 6, 9, 12, 13]
Elements in TreeSet object 2[6, 9, 12, 13]
Elements in TreeSet object 3[4, 6, 9, 12, 13]
Elements in TreeSet object 4[6, 9, 12, 13]

示例 2

输出

TreeSet: [1, 3, 6, 9, A, B, a, b]
Elements in TreeSet object 1[3, 6, 9, A, B, a]
Elements in TreeSet object 2[6, 9, A, B]
Elements in TreeSet object 3[3, 6, 9, A, B]
Elements in TreeSet object 4[6, 9, A, B, a]

示例 3

输出

Elements in TreeSet: 
1 C Programming in C 200
2 C++ Programming in C++ 340
3 VB Programming in Visual Basic 300
4 Java Programming in JAVA 400
5 DS Data Structure 400
6 SAD System Analysis and Design  400
7 SE Software eEngineering 400
Elements in TreeSet object 1[2 C++ Programming in C++ 340, 3 VB Programming in Visual Basic 300,
 4 Java Programming in JAVA 400, 5 DS Data Structure 400, 6 SAD System Analysis and Design  400]
Elements in TreeSet object 2[3 VB Programming in Visual Basic 300, 4 Java Programming in JAVA 400, 
5 DS Data Structure 400]
Elements in TreeSet object 3[2 C++ Programming in C++ 340, 3 VB Programming in Visual Basic 300, 
4 Java Programming in JAVA 400, 5 DS Data Structure 400]
Elements in TreeSet object 4[3 VB Programming in Visual Basic 300, 4 Java Programming in JAVA 400, 
5 DS Data Structure 400, 6 SAD System Analysis and Design  400]