How to declare an ArrayList with values?(如何用值声明一个 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.
这篇关于如何用值声明一个 ArrayList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何用值声明一个 ArrayList?


基础教程推荐
- 不推荐使用 Api 注释的描述 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 多个组件的复杂布局 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01