如何在Java中将Array转换为ArrayList?

将数组转换为ArrayList (Converting Array to ArrayList)

Given an Array, and we have to convert it into ArrayList in Java.

给定一个数组,我们必须将其转换为Java中的ArrayList。

To convert an Array to ArrayList, we use asList() method.

要将Array转换为ArrayList,我们使用asList()方法

asList()方法 (asList() method)

  • asList() method is available in java.util package.

    asList()方法在java.util包中可用。

  • asList() method is used to convert an Array to ArrayList.

    asList()方法用于将Array转换为ArrayList。

  • asList() method returns a converted List object which contains all of the elements in the Array.

    asList()方法返回一个转换后的List对象,其中包含Array中的所有元素。

  • asList() method does not throw any exception at the time of conversion from Array to ArrayList.

    从数组转换为ArrayList时, asList()方法不会引发任何异常。

  • It's a static method, it is accessible with the class name too. (i.e. If we try to execute with the class name then we will not get an error).

    这是一个静态方法,也可以使用类名进行访问。 (即,如果我们尝试使用类名执行,则不会收到错误)。

  • It's not a final method; it is overridable in child class if we want.

    这不是最终的方法; 如果需要,在子类中可以重写。

Syntax:

句法:

    public static List asList(array_name){
    }

Parameter(s):

参数:

array_name – represents the name of an array by which the list of the elements will be backed.

array_name –表示要用来备份元素列表的数组的名称。

Return value:

返回值:

The return type of this method is List, it returns the list view of the given array.

该方法的返回类型为List ,它返回给定数组的列表视图。

Example:

例:

// Java program to demonstrate the example of
// conversion of an Array to an ArrayList with 
// the help of asList() method of Arrays

import java.util.*;

public class ArrayToArrayList {
    public static void main(String[] args) {
        // array declaration
        Integer arr[] = {
            10,
            20,
            30,
            40,
            50
        };

        // Display array elements 
        System.out.println("Array elements");
        for (int i = 0; i < arr.length; ++i)
            System.out.println(arr[i]);

        System.out.println();

        // By using asList() method is used to convert 
        // Array to ArrayList

        List arr_list = Arrays.asList(arr);

        // Display ArrayList
        System.out.println("ArrayList Elements:");
        System.out.println(arr_list);
    }
}

Output

输出量

Array elements
10
20
30
40
50

ArrayList Elements:
[10, 20, 30, 40, 50]


翻译自: https://www.includehelp.com/java/convert-array-to-arraylist-in-java.aspx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值