如何将字符串数组的元素添加到字符串数组列表中? [英] How to add elements of a string array to a string array list?
问题描述
我试图将一个字符串数组作为参数传递给 Wetland 类的构造函数;我不明白如何将字符串数组的元素添加到字符串数组列表中.
I am trying to pass a string array as an argument to the constructor of Wetland class; I don't understand how to add the elements of string array to the string array list.
import java.util.ArrayList;
public class Wetland {
private String name;
private ArrayList<String> species;
public Wetland(String name, String[] speciesArr) {
this.name = name;
for (int i = 0; i < speciesArr.length; i++) {
species.add(speciesArr[i]);
}
}
}
推荐答案
你已经有内置的方法:-
You already have built-in method for that: -
List<String> species = Arrays.asList(speciesArr);
注意: - 您应该使用 List
不是 ArrayList
.
NOTE: - You should use List<String> species
not ArrayList<String> species
.
Arrays.asList
返回一个不同的 ArrayList
-> java.util.Arrays.ArrayList
,它不能被类型转换为 java.util.ArrayList
.
Arrays.asList
returns a different ArrayList
-> java.util.Arrays.ArrayList
which cannot be typecasted to java.util.ArrayList
.
那么你就不得不使用 addAll
方法,这不太好.所以只需使用 List
Then you would have to use addAll
method, which is not so good. So just use List<String>
注意: - Arrays.asList
返回的列表是一个固定大小的列表.如果您想向列表中添加某些内容,则需要创建另一个列表,并使用 addAll
向其中添加元素.所以,那么你最好采用下面的第二种方式:-
NOTE: - The list returned by Arrays.asList
is a fixed size list. If you want to add something to the list, you would need to create another list, and use addAll
to add elements to it. So, then you would better go with the 2nd way as below: -
String[] arr = new String[1];
arr[0] = "rohit";
List<String> newList = Arrays.asList(arr);
// Will throw `UnsupportedOperationException
// newList.add("jain"); // Can't do this.
ArrayList<String> updatableList = new ArrayList<String>();
updatableList.addAll(newList);
updatableList.add("jain"); // OK this is fine.
System.out.println(newList); // Prints [rohit]
System.out.println(updatableList); //Prints [rohit, jain]
这篇关于如何将字符串数组的元素添加到字符串数组列表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!