Three ways and comparison of Java array to List

Foreword:

This article introduces the comparison of the pros and cons of converting an array into a List in Java, as well as the comparison of application scenarios, and the analysis of the reasons for type conversion errors often made by programmers.

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

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

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 an exception at list.add("1"): UnsupportedOperationException.

Reason analysis : The
Arrays.asList(strArray)return value is java.util.Arraysa private static inner class in the class java.util.Arrays.ArrayList, it is not java.util.ArrayLista class. java.util.Arrays.ArrayListThe class has methods such as set(), get(), contains(), etc., but does not have add add()or delete remove()methods, so calling the add()method will report an error.

Usage scenario : Arrays.asList(strArray)The method can only be used after the array is converted into a List, and the values ​​in it do not need to be added or deleted. 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.

Arrays.asList(strArray)Convert the return value from ArrayList java.util.Arrays.ArrayListto java.util.ArrayList.

Key code :ArrayList<String> list = new ArrayList<String>(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: Successfully append an element "1".

[null, null, 1]

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

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

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

[null, null, 1]

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

Note: Attach the Collections.addAll()source code of the 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;
    }

4. Java8 can streamconvert 3 basic types of arrays to List through streams

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

An example of the conversion code 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's an array of Strings, you can use Streamstreams to convert like this:

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

--------------------------------------End of the text, the following is a concentrated response to the questions in the comments and explain --------------------------------------


Added: Answers to questions in comments

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

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

  1. Method 1: Addition and deletion are not supported
Integer[] intArray1 = new Integer[2];
List<Integer> list1 = Arrays.asList(intArray1);
System.out.println(list1);

operation result:

[null, null]
  1. Method 2: Support additions and deletions
Integer[] intArray2 = new Integer[2];
List<Integer> list2 = new ArrayList<Integer>(Arrays.asList(intArray2)) ;
list2.add(2);
System.out.println(list2);

operation result:

[null, null, 2]
  1. Method 3: Support additions and deletions, and the most efficient with large data volumes
Integer[] intArray3 = new Integer[2];
List<Integer> list3 = new ArrayList<Integer>(intArray3.length);
Collections.addAll(list3, intArray3);
list3.add(3);
System.out.println(list3);

operation result:

[null, null, 3]

To sum up, the correct way to convert an integer Integer[]array should be like this.List<Integer>

Guess the problem you encountered: Since the comment did not give the code that reported the error, I guess your error 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, use int[]or Integer[], which declaration method can be converted correctly List?
Answer: It can only be Integer[]converted List<Integer>directly, that is, only the wrapper type of the basic data type can be used List.

The reasons are analyzed as follows:

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

public interface List<E> extends Collection<E> {省略…}

Let Arrays.asList()'s look at the definition in the Java source code:

 public static <T> List<T> asList(T... a) {
        return new ArrayList<>(a);
    }
  • As can be seen from the above source code, Listwhen declaring, you need to pass a generic type <E>as a formal parameter, and the asList()parameter type is also a wildcard type in the generic type <T>. All generic types in Java must be reference types .

  • What is a reference type? Integeris a reference type, intwhat type is that? intis a primitive data type, not a reference type. That's why there is not in java List<int>, but only List<Integer>.

  • By analogy: the other 8 basic data typesbyte、short、int、long、float、double、char are not reference types , so none of the 8 basic data types can be used as formal parameters of List. HoweverString、数组、class、interface , reference types can be used as formal parameters of List, so there List<Runnable>are collections of interface types, collections of List<int[]>array types, and collections of List<String>classes. But there is no collection of basic types such as list<byte>, list<short>etc.

With the above basic knowledge, let's see why the second line of the following two lines of code can be compiled and passed, but the third line is compiled with an error?

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

Answer:

  • The second line of code, Arrays.asList()the input parameter of the method is a reference type int[], then the return value type must be List<int[]>, and its complete code is: List<int[]> intsArray = Arrays.asList(intArray1);, so the compilation is passed, no problem.
  • The third line reports an error, because the types on both sides of the equal sign are inconsistent, the left: List<Integer>, the right List<int[]>, so an error is reported when compiling.

Summarize

Now you should understand why it int[]can't be converted directly to List<Integer>, but Integer[]can be converted List<Integer>to . Because Listthe generic type in must be a reference type, it intis a basic data type, not a reference type, but intthe packaging type Integeris a classtype, which belongs to a reference type, so it Integercan be used as a Listformal parameter, List<Integer>which can exist in java, but there is no List<int>type.

When coding, we not only need to know what it is, but also why it is. By analyzing the JDK source code, we can get first-hand information, not only how to use it, but also why it is used.

I hope my answer is helpful to you. If you have any doubts, you can comment below the article. I will solve your doubts. If you like this article, please like and favorite it.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324174708&siteId=291194637