3.编写程序,使用ArrayList类实现数据的增删改查 (1)创建ArrayList对象; (2)使用add方法,添加”a“、”b“、”c“、”d“、”e“,5个元素 (3)使用remove方法,移除第3个元素”c“ (4)使用set方法,将第2个元素改为“F” (5)使用get方法,读取出数组中的第2个元素; (6)遍历输出ArrayList集合中的每个元素
时间: 2024-03-18 16:42:08 浏览: 33
下面是Java代码实现:
```java
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<String>(); // 创建ArrayList对象
arrayList.add("a"); // 添加元素
arrayList.add("b");
arrayList.add("c");
arrayList.add("d");
arrayList.add("e");
System.out.println("原始ArrayList集合:" + arrayList);
arrayList.remove(2); // 移除第3个元素
System.out.println("移除第3个元素后的ArrayList集合:" + arrayList);
arrayList.set(1, "F"); // 将第2个元素改为“F”
System.out.println("将第2个元素改为“F”后的ArrayList集合:" + arrayList);
String secondElement = arrayList.get(1); // 读取出数组中的第2个元素
System.out.println("数组中的第2个元素为:" + secondElement);
System.out.println("遍历输出ArrayList集合中的每个元素:");
for (int i = 0; i < arrayList.size(); i++) {
System.out.println(arrayList.get(i));
}
}
}
```
输出结果为:
```
原始ArrayList集合:[a, b, c, d, e]
移除第3个元素后的ArrayList集合:[a, b, d, e]
将第2个元素改为“F”后的ArrayList集合:[a, F, d, e]
数组中的第2个元素为:F
遍历输出ArrayList集合中的每个元素:
a
F
d
e
```
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)