如何用值声明一个 ArrayList?

How to declare an ArrayList with values?(如何用值声明一个 ArrayList?)

本文介绍了如何用值声明一个 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(Collectionc) (*)

    按照集合的迭代器返回的顺序构造一个包含指定集合元素的列表.

    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?