我试图将一个字符串数组作为参数传递给Wetland类的构造函数; 我不明白如何将字符串数组的元素添加到字符串数组列表中.
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]);
}
}
}
Run Code Online (Sandbox Code Playgroud)
Roh*_*ain 106
你已经有了内置的方法: -
List<String> species = Arrays.asList(speciesArr);
Run Code Online (Sandbox Code Playgroud)
注: -您应该使用List<String> species
没有ArrayList<String> species
.
Arrays.asList
返回一个不同的ArrayList
- > java.util.Arrays.ArrayList
不能被类型化java.util.ArrayList
.
那么你将不得不使用addAll
方法,这是不太好的.所以只需使用List<String>
注意: - 返回的列表Arrays.asList
是固定大小的列表.如果要向列表addAll
中添加内容,则需要创建另一个列表,并使用向其中添加元素.那么,你最好采用第二种方式: -
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]
Run Code Online (Sandbox Code Playgroud)
Rav*_*i A 15
我更喜欢这个,
List<String> temp = Arrays.asList(speciesArr);
species.addAll(temp);
Run Code Online (Sandbox Code Playgroud)
原因是Arrays.asList()方法将创建一个固定大小的List.因此,如果您直接将其存储到物种中,那么您将无法再添加任何元素,仍然不是只读的元素.你一定可以编辑你的物品.所以把它列入临时名单.
替代方案是,
Collections.addAll(species, speciesArr);
Run Code Online (Sandbox Code Playgroud)
在这种情况下,您可以添加,编辑,删除项目.
kei*_*sar 11
以为我会把这个添加到混合中:
Collections.addAll(result, preprocessor.preprocess(lines));
Run Code Online (Sandbox Code Playgroud)
这是Intelli建议的更改.
来自javadocs:
Adds all of the specified elements to the specified collection.
Elements to be added may be specified individually or as an array.
The behavior of this convenience method is identical to that of
<tt>c.addAll(Arrays.asList(elements))</tt>, but this method is likely
to run significantly faster under most implementations.
When elements are specified individually, this method provides a
convenient way to add a few elements to an existing collection:
<pre>
Collections.addAll(flavors, "Peaches 'n Plutonium", "Rocky Racoon");
</pre>
Run Code Online (Sandbox Code Playgroud)
您应该ArrayList
在尝试添加项目之前实例化您:
private List<String> species = new ArrayList<String>();
Run Code Online (Sandbox Code Playgroud)
Arrays.asList是Array和集合框架之间的桥梁,它返回一个由Array支持的固定大小List.
species = Arrays.asList(speciesArr);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
158103 次 |
最近记录: |