Home Java javaTutorial How to convert array to List in Java

How to convert array to List in Java

Apr 19, 2023 am 09:13 AM
java list

1. The most common method (not necessarily the best)

Through Arrays.asList(strArray) method, after converting the array to List, you cannot add or delete the List, you can only check and modify it. Otherwise throw an exception.

Key code: List list = Arrays.asList(strArray);

private void testArrayCastToListError() {   String[] strArray = new String[2];   List list = Arrays.asList(strArray);   //对转换后的list插入一条数据   list.add("1");   System.out.println(list);  }
Copy after login

Execution result:

Exception in thread "main" java.lang.UnsupportedOperationException  at java.util.AbstractList.add(AbstractList.java:148)  at java.util.AbstractList.add(AbstractList.java:108)  at com.darwin.junit.Calculator.testArrayCastToList(Calculator.java:19)  at com.darwin.junit.Calculator.main(Calculator.java:44)
Copy after login

The program throws at list.add("1") Exception: UnsupportedOperationException.

Reason analysis:

The return value of Arrays.asList(strArray) is a private static internal class java.util.Arrays.ArrayList in the java.util.Arrays class, which is not java.util. ArrayList class. The java.util.Arrays.ArrayList class has set(), get(), contains() and other methods, but it does not have add() or remove() methods, so calling the add() method will report an error.

Usage scenarios: The Arrays.asList(strArray) method can only be used after converting an array to a List. There is no need to add or delete values ​​in it. It can only be used as a data source to read.

2. After the array is converted to List, the method of adding, deleting, modifying and searching is supported.

Through the constructor of ArrayList, the return value of Arrays.asList(strArray) is changed from java to .util.Arrays.ArrayList is converted to java.util.ArrayList.

Key code: ArrayList

private void testArrayCastToListRight() {   String[] strArray = new String[2];   ArrayList<String> list = new ArrayList<String>(Arrays.asList(strArray)) ;   list.add("1");   System.out.println(list);  }
Copy after login

Execution result: An element "1" is successfully appended.

[null, null, 1]
Copy after login
Copy after login

Usage scenario: After converting the array to a List, you need to add, delete, modify, and query the List. This can be used when the amount of data in the List is not large.

3. Convert through the Collections.addAll() method of the collection tool class (the most efficient)

Convert through the Collections.addAll(arrayList, strArray) method, according to the length of the array Create a List of the same length, and then use the Collections.addAll() method to convert the elements in the array to binary and then add them to the List. This is the most efficient method.

Key code:

ArrayList< String> arrayList = new ArrayList<String>(strArray.length); Collections.addAll(arrayList, strArray);
Copy after login

Test:

private void testArrayCastToListEfficient(){   String[] strArray = new String[2];   ArrayList< String> arrayList = new ArrayList<String>(strArray.length);   Collections.addAll(arrayList, strArray);   arrayList.add("1");   System.out.println(arrayList);  }
Copy after login

Execution result: An element "1" is also successfully appended.

[null, null, 1]
Copy after login
Copy after login

Usage scenario: After converting the array to a List, you need to add, delete, modify, and query the List. When the amount of data in the List is huge, use it first, which can improve the operation speed.

Note: Attached is the source code of Collections.addAll() method:

public static <T> boolean addAll(Collection<? super T> c, T... elements) {         boolean result = false;         for (T element : elements)             result |= c.add(element);//result和c.add(element)按位或运算,然后赋值给result         return result;     }
Copy after login

Question Answer Question: If the array type is an integer array, will an error be reported when it is converted to List?

Answer: Tested in the JDK1.8 environment, there is no problem with these three conversion methods. safe to use. The method and test results for converting Integer[] integer array to List are as follows:

Method 1: Addition and deletion are not supported

Integer[] intArray1 = new Integer[2]; List<Integer> list1 = Arrays.asList(intArray1); System.out.println(list1);
Copy after login

Running results:

[null, null]
Copy after login

Method 2: Supports additions and deletions

Integer[] intArray2 = new Integer[2]; List<Integer> list2 = new ArrayList<Integer>(Arrays.asList(intArray2)) ; list2.add(2); System.out.println(list2);
Copy after login

Run results:

[null, null, 2]
Copy after login

Method 3: Supports additions and deletions, and is the most efficient for large amounts of data

Integer[] intArray3 = new Integer[2]; List<Integer> list3 = new ArrayList<Integer>(intArray3.length); Collections.addAll(list3, intArray3); list3.add(3); System.out.println(list3);
Copy after login

Running result:

[null, null, 3]
Copy after login

In summary, integer Integer[] array is converted to List

Error-prone points: Possible errors may be converted like this :

int[] intArray1 = new int[2]; List<Integer> list1 = Arrays.asList(intArray1);//此处报错!!!
Copy after login

Reason for the error: The types on both sides of the equal sign are inconsistent, and of course the compilation fails. See below for analysis.

So when declaring an array, should you use int[] or Integer[], which declaration method can correctly convert it to List?

Answer: You can only use Integer[] to convert List

The reasons are analyzed as follows:

Let’s take a look at the definition of List in the Java source code (don’t be afraid that you can’t understand the source code, let me analyze it, it’s very easy to understand):

public interface List<E> extends Collection<E> {省略&hellip;}
Copy after login

Let’s look at the Java source code definition of Arrays.asList():

public static List asList(T... a) {     return new ArrayList<>(a); }
Copy after login
  • As can be seen from the above source code, when List is declared, You need to pass a generic

  • What is a reference type? Integer is a reference type, so what type is int? Int is a basic data type, not a reference type. This is why there is no List in java

  • By analogy: the other 8 basic data types byte, short, int, long, float, double, and char are not reference types, so the 8 basic data types No data type can be used as a formal parameter of List. However, String, array, class, and interface are reference types and can be used as formal parameters of List, so there exists List

With the above basic knowledge, let’s look at why the following two lines of code are The second line of code compiles successfully, but the third line compiles and reports an error?

int[] intArray1 = new int[1];  Arrays.asList(intArray1);//编译不报错 List<Integer> list1 = Arrays.asList( intArray1);//编译报错
Copy after login

Answer:

  • The second line of code, the input parameter of the Arrays.asList() method is a reference Type int[], then the return value type must be List

  • The third line reports an error because the types on both sides of the equal sign are inconsistent. The left side: List

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

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

How to Run Your First Spring Boot Application in Spring Tool Suite? How to Run Your First Spring Boot Application in Spring Tool Suite? Feb 07, 2025 pm 12:11 PM

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo

See all articles