arraylist add
时间: 2023-10-12 20:06:20 浏览: 53
ArrayList 的 add 方法用于将元素添加到列表的末尾。它的语法如下:
```java
boolean add(E element)
```
其中,E 是要添加的元素的类型,element 是要添加的元素。这个方法会返回一个 boolean 值,表示添加是否成功。
下面是一个示例:
```java
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> fruits = new ArrayList<>();
// 添加元素到 ArrayList
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
// 打印 ArrayList
System.out.println(fruits);
}
}
```
输出结果:
```
相关问题
kotlin arraylist add
在Kotlin中,可以使用`add()`方法向ArrayList中添加元素。下面是一个示例代码:
```kotlin
fun main() {
val arrayList = arrayListOf<String>()
arrayList.add("1")
arrayList.add("2")
arrayList.add("3")
println(arrayList) // 输出:[1, 2, 3]
}
```
在上面的代码中,我们首先创建了一个空的ArrayList,然后使用`add()`方法向ArrayList中添加了三个元素。最后,我们使用`println()`函数打印ArrayList的内容。
java arraylist add
Java中的ArrayList是一种动态数组,可以通过add方法向其中添加元素。例如:
ArrayList<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("orange");
上述代码创建了一个String类型的ArrayList,并向其中添加了三个元素。可以使用get方法获取指定位置的元素,例如:
String fruit = list.get(1); // 获取第二个元素,即"banana"
也可以使用remove方法删除指定位置的元素,例如:
list.remove(2); // 删除第三个元素,即"orange"
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.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)