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); }
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< String> arrayList = new ArrayList<String>(strArray.length); Collections.addAll(arrayList, strArray);
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); }
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; }
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);
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);
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);
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);//此处报错!!!
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> {省略…}
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);//编译报错
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!