ArrayList or List declaration in 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
:
Stream.of("xyz", "abc").collect(Collectors.toList());
当然,您可以使用接受 Collection
的构造函数创建一个新对象。 :
List<String> x = new ArrayList<>(Arrays.asList("xyz", "abc"));
提示:docs包含非常有用的信息,通常包含您正在寻找的答案。例如,这里是 ArrayList
的构造函数类:
-
Constructs an empty list with an initial capacity of ten.
ArrayList(Collection<? extends E> c)
(*)Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.
ArrayList(int initialCapacity)
Constructs an empty list with the specified initial capacity.
关于java - 如何用值声明一个 ArrayList?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21696784/