写一个treeset的例子
时间: 2024-05-07 19:21:31 浏览: 14
以下是一个使用TreeSet的例子:
```java
import java.util.TreeSet;
public class TreeSetExample {
public static void main(String[] args) {
// 创建一个TreeSet实例,存储整数类型数据
TreeSet<Integer> treeSet = new TreeSet<>();
// 添加数据
treeSet.add(5);
treeSet.add(3);
treeSet.add(7);
treeSet.add(1);
treeSet.add(9);
// 输出TreeSet中的数据
System.out.println("TreeSet中的数据为:");
for (Integer num : treeSet) {
System.out.print(num + " ");
}
System.out.println();
// 获取并输出第一个元素
Integer first = treeSet.first();
System.out.println("第一个元素是:" + first);
// 获取并输出最后一个元素
Integer last = treeSet.last();
System.out.println("最后一个元素是:" + last);
// 获取并输出小于等于指定元素的最大元素
Integer floor = treeSet.floor(6);
System.out.println("小于等于6的最大元素是:" + floor);
// 获取并输出大于等于指定元素的最小元素
Integer ceiling = treeSet.ceiling(4);
System.out.println("大于等于4的最小元素是:" + ceiling);
// 删除指定元素
treeSet.remove(3);
// 输出删除指定元素后的TreeSet中的数据
System.out.println("删除元素3后TreeSet中的数据为:");
for (Integer num : treeSet) {
System.out.print(num + " ");
}
System.out.println();
}
}
```
输出结果为:
```
TreeSet中的数据为:
1 3 5 7 9
第一个元素是:1
最后一个元素是:9
小于等于6的最大元素是:5
大于等于4的最小元素是:5
删除元素3后TreeSet中的数据为:
1 5 7 9
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)