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 Hashmap 中的值求和 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 存储 20 位数字的数据类型 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
