1.创建一个集合类HashSet对象hs,并向集合中添加几个字符串”abc”,”efg”,”hij”,然后通过遍历器进行迭代输出
时间: 2024-05-12 07:20:13 浏览: 21
代码如下:
```java
import java.util.HashSet;
import java.util.Iterator;
public class HashSetDemo {
public static void main(String[] args) {
HashSet<String> hs = new HashSet<String>();
hs.add("abc");
hs.add("efg");
hs.add("hij");
Iterator<String> it = hs.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}
```
输出结果如下:
```
abc
hij
efg
```
相关问题
创建一个集合类HashSet对象hs,并向集合中添加几个字符串”abc”,”efg”,”hij”,然后通过遍历器进行迭代输出
以下是Java代码示例:
```java
import java.util.HashSet;
import java.util.Iterator;
public class HashSetExample {
public static void main(String[] args) {
HashSet<String> hs = new HashSet<>();
hs.add("abc");
hs.add("efg");
hs.add("hij");
Iterator<String> iterator = hs.iterator();
while (iterator.hasNext()) {
String str = iterator.next();
System.out.println(str);
}
}
}
```
输出结果如下:
```
hij
abc
efg
```
在HashSet集合中添加三个String类对象,期中两个字符串内容相同,最后输出集合所有元素。用Java集合类编写程序
好的,根据您的要求,下面是一个简单的Java程序来实现您的要求:
```java
import java.util.HashSet;
public class HashSetExample {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
// 添加三个String类对象
set.add("hello");
set.add("world");
set.add("hello");
// 输出集合所有元素
for (String str : set) {
System.out.println(str);
}
}
}
```
运行结果为:
```
hello
world
```
可以看出,HashSet集合中只保留了不重复的元素,即去掉了两个内容相同的"hello"字符串。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)