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?
基础教程推荐
- Java ECDSAwithSHA256 签名长度不一致 2022-01-01
- 在springboot中如何给mybatis加拦截器 2023-04-29
- 在java中使用xpath和selenium解析HTML表格数据 2022-01-01
- JPA惰性列表上的流 2022-01-01
- Maven:无效的目标版本:10 2022-01-01
- 控制台应用程序中的 Java 键盘输入解析 2022-01-01
- 将 double 转换为 Int,向下舍入 2022-01-01
- 如何在相机中应用自定义滤镜 [Surfaceview 预览]. 2022-01-01
- doFilter()是在servlet的工作完成之前还是之后执行的? 2022-01-01
- 将 Windows 证书导入 Java 2022-01-01
