如何在 Java 中创建一个包含值的列表?


我们可以利用 Arrays.asList() 方法使用单个语句获取指定元素的列表。

语法

public static <T> List<T> asList(T... a)

返回由指定数组支持的固定大小的列表。(对返回列表的更改将“写入”数组。)

类型参数

  • T − 数组的运行时类型。

参数

  • a − 该列表将使用该数组作为支持。

返回

指定数组的列表视图

如果我们使用 Arrays.asList(),则无法从列表中添加/删除元素。因此,我们使用该列表作为 ArrayList 构造函数的输入以确保该列表可修改。

示例

以下示例显示如何使用单个语句创建包含多个项目的列表。

Open Compiler
package com.tutorialspoint; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class CollectionsDemo { public static void main(String[] args) { // Create a list object List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3)); // print the list System.out.println(list); list.add(4); System.out.println(list); } }

Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

输出

将产生以下结果 −

[1, 2, 3]
[1, 2, 3, 4]

更新于: 2022 年 5 月 10 日

733 次浏览

开启你的职业生涯

完成课程以获得认证

开始行动
广告