使用LinkedHashSet存储以下元素:"王昭君","王昭君","西施","杨玉环","貂蝉"。使用迭代器和增强for循环遍历LinkedHashSet
时间: 2024-06-05 10:05:38 浏览: 19
使用LinkedHashSet存储这些字符串元素,LinkedHashSet是一个有序的哈希集合,它会保持元素插入的顺序。当我们添加重复元素时, LinkedHashSet只会保留一个。现在,我们首先创建一个 LinkedHashSet,然后添加指定的元素,接着使用迭代器和增强for循环遍历这个集合。
```java
import java.util.LinkedHashSet;
import java.util.Iterator;
public class Main {
public static void main(String[] args) {
// 创建 LinkedHashSet 并添加元素
LinkedHashSet<String> historicalBeauties = new LinkedHashSet<>();
historicalBeauties.add("王昭君");
historicalBeauties.add("王昭君"); // 只会保留一个 "王昭君"
historicalBeauties.add("西施");
historicalBeauties.add("杨玉环");
historicalBeauties.add("貂蝉");
// 使用迭代器遍历
Iterator<String> iterator = historicalBeauties.iterator();
System.out.println("Using an iterator:");
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
// 使用增强for循环遍历
System.out.println("\nUsing enhanced for loop:");
for (String beauty : historicalBeauties) {
System.out.println(beauty);
}
}
}
```
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.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)