java TreeSet取指定索引的值
时间: 2024-06-11 14:05:06 浏览: 12
Java TreeSet 不支持按索引访问元素,因为它是一个基于红黑树实现的有序集合,元素的顺序是由元素的值决定的。如果您需要访问 TreeSet 中的元素,您可以使用迭代器、foreach 循环或 toArray() 方法。例如:
```
TreeSet<String> set = new TreeSet<>();
set.add("apple");
set.add("banana");
set.add("cherry");
// 使用迭代器访问
Iterator<String> iterator = set.iterator();
for (int i = 0; i < 2; i++) {
if (iterator.hasNext()) {
String element = iterator.next();
System.out.println(element);
}
}
// 使用 foreach 循环访问
int index = 0;
for (String element : set) {
if (index == 1) {
System.out.println(element);
break;
}
index++;
}
// 使用 toArray() 方法访问
String[] array = set.toArray(new String[0]);
if (array.length > 2) {
System.out.println(array[2]);
}
```
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)