Comparison of the advantages and disadvantages of three methods of converting arrays to List in Java

Preface

This article introduces the comparison of the pros and cons of the three cases of converting an array to a List in Java, as well as the comparison of application scenarios, and the analysis of the causes of type conversion errors that programmers often make.


1. The most common way (not necessarily the best) is
through the Arrays.asList(strArray) way, after the array is converted to the List, the List cannot be added or deleted, but the list can only be checked and changed, otherwise an exception will be thrown.

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

Results of the:

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)

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 the java.util.ArrayList class. The java.util.Arrays.ArrayList class has set(), get(), contains() and other methods, but it does not have the add() or remove() method, so calling the add() method will report an error.

Usage scenario: The Arrays.asList(strArray) method can only be used after the array is converted to a List. There is no need to add or delete the values ​​in it. It is only used as a data source for reading.


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

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

关键代码:ArrayList list = new ArrayList(Arrays.asList(strArray)) ;

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" was successfully added.

[null, null, 1]

Use scenario: You need to add, delete, modify, and check the List after converting the array to a List. It can be used when the amount of data in the List is not large.


Three. Through the collection tool class Collections.addAll () method (the most efficient)

Convert through Collections.addAll(arrayList, strArray) method, create a List of the same length according to the length of the array, and then convert the elements in the array to binary through the Collections.addAll() method, and then add it to the List 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: also successfully added an element "1".

[null, null, 1]

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

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

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

Four. Java8 can convert 3 basic types of arrays to List through stream

If the JDK version is above 1.8, you can use stream to quickly convert the following three types of arrays to List, which are int[], long[], double[], and other data types such as short[], byte[], char[ ], currently not supported in JDK1.8. Since this is just an encapsulation of a common method, a new way of array to List conversion is no longer included. For the time being, it is a common tool method that java streams to us.

The conversion code example is as follows:

List<Integer> intList= Arrays.stream(new int[] {
    
     1, 2, 3, }).boxed().collect(Collectors.toList());
List<Long> longList= Arrays.stream(new long[] {
    
     1, 2, 3 }).boxed().collect(Collectors.toList());
List<Double> doubleList= Arrays.stream(new double[] {
    
     1, 2, 3 }).boxed().collect(Collectors.toList());

If it is an array of String or reference type (Integer or object, etc.), you can also use Stream to convert like this:

String[] arrays = {
    
    "tom", "jack", "kate"};
List<String> stringList= Stream.of(arrays).collect(Collectors.toList());

additional

When declaring an array, use int[] or Integer[], which declaration method can be converted to List correctly?

Answer: You can only use Integer[] to convert to List, that is, you can only use the packaging type of the basic data type to directly convert to List.

The reasons are as follows:

Let's look at the definition of List in the Java source code (don't be afraid to not understand the source code, it's easy to understand according to my analysis):

public interface List extends Collection {omitted...}
Look at the definition of Arrays.asList() in Java source code:

 public static <T> List<T> asList(T... a) {
    
    
        return new ArrayList<>(a);
    }

As can be seen from the above source code, when List is declared, a generic type needs to be passed as a formal parameter, and the parameter type of asList() is also a wildcard type in generics. All generic types in Java must be reference types.

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

Infer other things: the other eight basic data types byte, short, int, long, float, double, and char are not reference types, so none of the eight basic data types can be used as formal parameters of List. However, String, array, class, and interface are reference types, which can all be used as formal parameters of List, so there is a collection of List interface types, a collection of List<int[]> array types, and a collection of List classes. But there are no basic types of collections such as lists and lists.

With the above basic knowledge, let’s look at why the second line of the following two lines of code can compile and pass, but the third line compiles an error?

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

answer:

In 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<int[]>, and the complete code is: List<int[]> intsArray = Arrays. asList(intArray1);, so the compilation passes, no problem.

The third line reports an error, because the types on both sides of the equal sign are inconsistent, on the left: List, on the right List<int[]>, so an error is reported at compile time.

Guess you like

Origin blog.csdn.net/qq_36551991/article/details/110007218