Comparison of several ways of Java array to List

Posted by patrickm on Mon, 27 Dec 2021 07:42:30 +0100

In actual development, we often encounter the scene of converting arrays into collections. Various processing methods are as follows:

Suppose we have an array of strings

String[] arr = {"1", "2", "3"};

The most brainless way (not necessarily the worst)

Define a new set, traverse the array, and then add it to the set after data format conversion. I won't say much about this method. It's not difficult to implement, but the code is not concise enough, but some operations can be done during traversal, which makes the actual use more flexible

String[] arr = {"1", "2", "3"};
List<Integer> integers = new ArrayList<>();
for (String s : arr) {
    integers.add(Integer.valueOf(s));
}

Use arrays Aslist method (easiest to step on the pit)

Via arrays Aslist (strarray) mode: after the array is converted into a List, the List cannot be added or deleted, but can only be checked and modified, otherwise an exception will be thrown.

String[] arr = {"1", "2", "3"};
List<String> strings = Arrays.asList(arr);
// The following code will report an error
strings.add("4");

Adding or deleting this object will report an error and throw an exception: Unsupported operation exception

Reason: arrays The return value of aslist (strarray) is Java util. A private static inner class in the arrays class, Java util. Arrays. ArrayList, which is not Java util. ArrayList class. java.util.Arrays.ArrayList class has set(), get(), contains() and other methods, but does not have add() or remove() methods, so calling add() method will report an error.

Usage scene: arrays The aslist (strarray) method can only be used after converting an array into a List. There is no need to add or delete the values in it. It is only used for data source reading.

Use arrays Aslist with ArrayList constructor (not used by many people)

String[] arr = {"1", "2", "3"};
ArrayList list = new ArrayList(Arrays.asList(arr)) ;
// The following code will not report an error
list.add("4");

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

Through the collection tool class collections Addall() method (most efficient)

Via collections Addall (ArrayList, strarray) mode conversion, create a List with the same length according to the length of the array, and then through collections The addall () method converts the elements in the array into binary and then adds them to the List, which is the most efficient method.

String[] arr = {"1", "2", "3"};
List<String> strings = new ArrayList<>(arr.length);
Collections.addAll(strings, arr);
// The following code will not report an error
strings.add("4");

Java 8 can convert three basic types of arrays into lists through stream streams

If the JDK version is above 1.8, you can use stream to quickly convert the following three arrays into lists, namely int [], long [], double [], and other data types, such as short [], byte [], char [], in jdk1 Not supported in 8. Since this is only the encapsulation of common methods, it will no longer include a new method of converting array to List. It is a common tool and method sent to us by java stream for the time being.

// Number type
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 a string array

String[] arr = {"1", "2", "3"};
List<String> strings = Stream.of(arr).collect(Collectors.toList());

extend

If the element in the array is of basic data type, an error will be reported if it is converted to List, for example:

// The following code will report an error
int[] intArray = new int[2];
List<Integer> list = Arrays.asList(intArray);

The causes are analyzed as follows:

Let's look at the definition of List in Java source code

public interface List<E> extends Collection<E> {
	...
}

Let's look at arrays Aslist() is defined 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, when declaring a List, you need to pass a generic type as a formal parameter, and the asList() parameter type is also a generic type in the generic type. All generics 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.
  • Draw inferences from one example: 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 the list. However, String, array, class and interface are reference types and can be used as formal parameters of list. Therefore, there are collections of list interface type, list array type and list class. But there are no collections of basic types such as list and list.

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

int[] intArray = new int[2]; 
Arrays.asList(intArray);// Compile without error
List<Integer> list = Arrays.asList( intArray);// Compilation error

answer:

  • The second line of code, arrays The input parameter of the aslist () method is an int [] of reference type, so the return value type must be List, and its complete code is: List intsarray = arrays asList(intArray1);, So compile through, no problem.
  • The third line reports an error because the types on both sides of the equal sign are inconsistent. On the left: List < integer >, on the right: List < int [] >, so an error is reported during compilation.

Topics: Java JavaSE