search
HomeJavajavaTutorialHow to convert array to List in Java

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);  }

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)

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);  }</string></string>

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

[null, null, 1]

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 arrayList = new ArrayList<string>(strArray.length); Collections.addAll(arrayList, strArray);</string>

Test:

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

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

[null, null, 1]

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;     }</t>

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);</integer>

Running results:

[null, null]

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);</integer></integer>

Run results:

[null, null, 2]

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);</integer></integer>

Running result:

[null, null, 3]

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);//此处报错!!!</integer>

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> {省略…}</e></e>

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

public static List asList(T... a) {     return new ArrayList(a); }
  • 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);//编译报错</integer>

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
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
What aspects of Java development are platform-dependent?What aspects of Java development are platform-dependent?Apr 26, 2025 am 12:19 AM

Javadevelopmentisnotentirelyplatform-independentduetoseveralfactors.1)JVMvariationsaffectperformanceandbehavioracrossdifferentOS.2)NativelibrariesviaJNIintroduceplatform-specificissues.3)Filepathsandsystempropertiesdifferbetweenplatforms.4)GUIapplica

Are there performance differences when running Java code on different platforms? Why?Are there performance differences when running Java code on different platforms? Why?Apr 26, 2025 am 12:15 AM

Java code will have performance differences when running on different platforms. 1) The implementation and optimization strategies of JVM are different, such as OracleJDK and OpenJDK. 2) The characteristics of the operating system, such as memory management and thread scheduling, will also affect performance. 3) Performance can be improved by selecting the appropriate JVM, adjusting JVM parameters and code optimization.

What are some limitations of Java's platform independence?What are some limitations of Java's platform independence?Apr 26, 2025 am 12:10 AM

Java'splatformindependencehaslimitationsincludingperformanceoverhead,versioncompatibilityissues,challengeswithnativelibraryintegration,platform-specificfeatures,andJVMinstallation/maintenance.Thesefactorscomplicatethe"writeonce,runanywhere"

Explain the difference between platform independence and cross-platform development.Explain the difference between platform independence and cross-platform development.Apr 26, 2025 am 12:08 AM

Platformindependenceallowsprogramstorunonanyplatformwithoutmodification,whilecross-platformdevelopmentrequiressomeplatform-specificadjustments.Platformindependence,exemplifiedbyJava,enablesuniversalexecutionbutmaycompromiseperformance.Cross-platformd

How does Just-In-Time (JIT) compilation affect Java's performance and platform independence?How does Just-In-Time (JIT) compilation affect Java's performance and platform independence?Apr 26, 2025 am 12:02 AM

JITcompilationinJavaenhancesperformancewhilemaintainingplatformindependence.1)Itdynamicallytranslatesbytecodeintonativemachinecodeatruntime,optimizingfrequentlyusedcode.2)TheJVMremainsplatform-independent,allowingthesameJavaapplicationtorunondifferen

Why is Java a popular choice for developing cross-platform desktop applications?Why is Java a popular choice for developing cross-platform desktop applications?Apr 25, 2025 am 12:23 AM

Javaispopularforcross-platformdesktopapplicationsduetoits"WriteOnce,RunAnywhere"philosophy.1)ItusesbytecodethatrunsonanyJVM-equippedplatform.2)LibrarieslikeSwingandJavaFXhelpcreatenative-lookingUIs.3)Itsextensivestandardlibrarysupportscompr

Discuss situations where writing platform-specific code in Java might be necessary.Discuss situations where writing platform-specific code in Java might be necessary.Apr 25, 2025 am 12:22 AM

Reasons for writing platform-specific code in Java include access to specific operating system features, interacting with specific hardware, and optimizing performance. 1) Use JNA or JNI to access the Windows registry; 2) Interact with Linux-specific hardware drivers through JNI; 3) Use Metal to optimize gaming performance on macOS through JNI. Nevertheless, writing platform-specific code can affect the portability of the code, increase complexity, and potentially pose performance overhead and security risks.

What are the future trends in Java development that relate to platform independence?What are the future trends in Java development that relate to platform independence?Apr 25, 2025 am 12:12 AM

Java will further enhance platform independence through cloud-native applications, multi-platform deployment and cross-language interoperability. 1) Cloud native applications will use GraalVM and Quarkus to increase startup speed. 2) Java will be extended to embedded devices, mobile devices and quantum computers. 3) Through GraalVM, Java will seamlessly integrate with languages ​​such as Python and JavaScript to enhance cross-language interoperability.

See all articles

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

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.