Java 中的 ArrayList 或 List 声明 https://stackoverflow.com/questions/12321177/arraylist-declaration-java已提问并回答了如何声明空ArrayList
但如何声明带有值的 ArrayList 呢?
我已尝试以下操作,但它返回语法错误:
import java.io.IOException;
import java.util.ArrayList;
public class test {
public static void main(String[] args) throws IOException {
ArrayList<String> x = new ArrayList<String>();
x = ['xyz', 'abc'];
}
}
在 Java 9+ 中你可以这样做:
var x = List.of("xyz", "abc");
// 'var' works only for local variables
Java 8 使用Stream https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html:
Stream.of("xyz", "abc").collect(Collectors.toList());
当然,您可以使用接受的构造函数创建一个新对象Collection http://docs.oracle.com/javase/8/docs/api/java/util/Collection.html:
List<String> x = new ArrayList<>(Arrays.asList("xyz", "abc"));
提示:docs http://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html包含非常有用的信息,通常包含您正在寻找的答案。例如,下面是ArrayList
class:
-
ArrayList() http://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#ArrayList--
构造一个初始容量为 10 的空列表。
-
ArrayList(Collection<? extends E> c) http://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#ArrayList-java.util.Collection- (*)
构造一个包含指定集合的元素的列表,按照集合迭代器返回这些元素的顺序排列。
-
ArrayList(int initialCapacity) http://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#ArrayList-int-
构造一个具有指定初始容量的空列表。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)