java分别创建一个thing集合和一个整数集合,用for循环往集合中添加十个集合元素,测试调用集合的相关操作方法,输出测试结果
时间: 2024-05-15 07:13:26 浏览: 18
好的,下面是Java代码示例:
```java
import java.util.ArrayList;
import java.util.List;
public class CollectionTest {
public static void main(String[] args) {
// 创建一个thing集合
List<String> thingList = new ArrayList<>();
// 往thing集合中添加10个元素
for (int i = 1; i <= 10; i++) {
thingList.add("thing" + i);
}
// 测试调用集合的相关操作方法
System.out.println("thing集合中元素的个数:" + thingList.size()); // 输出:10
System.out.println("thing集合是否为空:" + thingList.isEmpty()); // 输出:false
System.out.println("thing集合是否包含元素thing5:" + thingList.contains("thing5")); // 输出:true
thingList.remove("thing3");
System.out.println("移除元素thing3后,thing集合中元素的个数:" + thingList.size()); // 输出:9
System.out.println("thing集合中第五个元素是:" + thingList.get(4)); // 输出:thing5
// 创建一个整数集合
List<Integer> intList = new ArrayList<>();
// 往整数集合中添加10个元素
for (int i = 1; i <= 10; i++) {
intList.add(i);
}
// 测试调用集合的相关操作方法
System.out.println("整数集合中元素的个数:" + intList.size()); // 输出:10
System.out.println("整数集合是否为空:" + intList.isEmpty()); // 输出:false
System.out.println("整数集合是否包含元素5:" + intList.contains(5)); // 输出:true
intList.remove(Integer.valueOf(3));
System.out.println("移除元素3后,整数集合中元素的个数:" + intList.size()); // 输出:9
System.out.println("整数集合中第五个元素是:" + intList.get(4)); // 输出:5
}
}
```
运行上述代码,控制台将输出如下结果:
```
thing集合中元素的个数:10
thing集合是否为空:false
thing集合是否包含元素thing5:true
移除元素thing3后,thing集合中元素的个数:9
thing集合中第五个元素是:thing5
整数集合中元素的个数:10
整数集合是否为空:false
整数集合是否包含元素5:true
移除元素3后,整数集合中元素的个数:9
整数集合中第五个元素是:5
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)