Home  >  Article  >  Java  >  How to convert java array into list

How to convert java array into list

DDD
DDDOriginal
2023-12-22 17:06:591477browse

To convert a java array into a list, you can use the Arrays.asList() method in Java's Collections class. First define an array of integers and then convert it to a List using the "Arrays.asList()" method. The converted List is stored in the list variable and printed. Note that the "Arrays.asList()" method returns a fixed-size List based on the original array and so on.

How to convert java array into list

# Operating system for this tutorial: Windows 10 system, Dell G3 computer.

To convert a Java array into a List, you can use the Arrays.asList() method in Java's Collections class. Here is a simple example:

import java.util.Arrays;  
import java.util.List;  
  
public class ArrayToListExample {  
    public static void main(String[] args) {  
        // 定义一个整数数组  
        int[] array = {1, 2, 3, 4, 5};  
  
        // 将数组转换为List  
        List<Integer> list = Arrays.asList(array);  
  
        // 打印List内容  
        System.out.println(list);  
    }  
}

In the above example, we first define an array of integers and then convert it to a List using the Arrays.asList() method. The converted List is stored in the list variable and printed.

It should be noted that the Arrays.asList() method returns a fixed-size List, which is based on the original array. This means you cannot add or remove elements, but you can modify existing elements. If you need a modifiable, dynamically sized List, you can use the ArrayList class, for example:

import java.util.ArrayList;  
import java.util.Arrays;  
import java.util.List;  
  
public class ArrayToListExample {  
    public static void main(String[] args) {  
        // 定义一个整数数组  
        int[] array = {1, 2, 3, 4, 5};  
  
        // 将数组转换为ArrayList  
        List<Integer> list = new ArrayList<>(Arrays.asList(array));  
  
        // 添加元素到List  
        list.add(6);  
        list.add(7);  
  
        // 打印List内容  
        System.out.println(list);  
    }  
}

In this example, we first convert the array into a fixed-size List, and then use the constructor of the ArrayList class The function converts it into an ArrayList that can be modified. We then added two elements to the list and printed out the contents of the list.

The above is the detailed content of How to convert java array into list. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn