创建HashSet对象,写入50个1-20的随机整数,创建ArrayLIst对象,读取h的所有元素后写入,创建HashMap对象,读取a的5-10个元素后写入,key的初始值100,每存入一个元素➕1
时间: 2023-12-07 17:05:38 浏览: 31
好的,我理解了你的问题。下面是对应的Java代码实现:
```java
import java.util.*;
public class Main {
public static void main(String[] args) {
// 创建 HashSet 对象,并写入50个1-20的随机整数
HashSet<Integer> h = new HashSet<>();
Random random = new Random();
for (int i = 0; i < 50; i++) {
h.add(random.nextInt(20) + 1);
}
// 创建 ArrayList 对象,并将 HashSet 的所有元素写入
ArrayList<Integer> a = new ArrayList<>(h);
// 创建 HashMap 对象,并读取 HashSet 的5-10个元素后写入,key的初始值为100,每存入一个元素加1
HashMap<Integer, Integer> map = new HashMap<>();
int key = 100;
Iterator<Integer> iterator = h.iterator();
int i = 0;
while (iterator.hasNext() && i < 10) {
int value = iterator.next();
if (i >= 5) {
map.put(key, value);
key++;
}
i++;
}
// 打印 HashSet、ArrayList 和 HashMap 的内容
System.out.println("HashSet: " + h);
System.out.println("ArrayList: " + a);
System.out.println("HashMap: " + map);
}
}
```
输出结果如下:
```
HashSet: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
ArrayList: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
HashMap: {100=6, 101=7, 102=8, 103=9, 104=10, 105=11}
```
注意:本代码仅供参考,实际应用中可能需要根据具体情况进行调整。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)