如何用值声明一个 ArrayList?
ArrayList or List declaration in Java质疑并回答了如何声明一个空的ArrayList
但是如何声明一个带有值的 ArrayList?
ArrayList or List declaration in Java has questioned and answered how to declare an empty ArrayList
but how do I declare an ArrayList with values?
我尝试了以下方法,但它返回语法错误:
I've tried the following but it returns a syntax error:
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+ 中你可以这样做:
In Java 9+ you can do:
var x = List.of("xyz", "abc");
// 'var' works only for local variables
<小时>
Java 8 使用 Stream
:
Stream.of("xyz", "abc").collect(Collectors.toList());
<小时>
当然,您可以使用接受 集合
:
List<String> x = new ArrayList<>(Arrays.asList("xyz", "abc"));
<小时>
提示:docs 包含非常通常包含您正在寻找的答案的有用信息.例如,这里是 ArrayList
类的构造函数:
Tip: The docs contains very useful information that usually contains the answer you're looking for. For example, here are the constructors of the ArrayList
class:
ArrayList()
构造一个初始容量为 10 的空列表.
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.
相关文章