Preface:

This article introduces the advantages and disadvantages of the three cases of array to List in Java, as well as the comparison of application scenarios, and programmers often make type conversion error analysis.

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

After arrays.aslist (strArray) is converted from an array to a List, you can’t add or delete the List, but only check and change the List, otherwise exceptions are thrown. Arrays.aslist (strArray) = arrays.aslist (strArray);

private void testArrayCastToListError(a) {
  String[] strArray = new String[2];
  List list = Arrays.asList(strArray);
  // Insert data into the converted list
  list.add("1");
  System.out.println(list);
 }
Copy the code

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)
Copy the code

Program in the list. The add (” 1 “), an exception is thrown, UnsupportedOperationException. Cause analysis: the Arrays asList (strArray), the return value is the Java. Util. Java Arrays class in a private static inner class. Util. Arrays. The ArrayList, it is not a Java. Util. The ArrayList class. Java. Util. Arrays. The ArrayList class has set (), the get (), the contains () method, but I don’t have to add the add () or delete the remove () method, so call the add () method will be an error. Usage scenario: Arrays.asList(strArray) mode can only be used to convert an array to a List, without adding or deleting the values in the List, and can only be read as the data source.

After the array is converted to List, it supports adding, deleting, modifying and checking

Through the ArrayList constructor, Arrays. AsList (strArray) return values by Java. Util. Arrays. The ArrayList into Java. Util. The ArrayList. ArrayList list = new ArrayList(Arrays.aslist (strArray));

private void testArrayCastToListRight(a) {
  String[] strArray = new String[2];
  ArrayList<String> list = new ArrayList<String>(Arrays.asList(strArray)) ;
  list.add("1");
  System.out.println(list);
}
Copy the code

Result: Append an element “1” successfully.

[null.null.1]
Copy the code

Application scenario: After the array is converted to a List, you can add, delete, modify, and query the List. This operation can be used when the amount of data in the List is small.

3. Using the Collections utility class collections.addall () method (most efficient)

The collections.addall (arrayList, strArray) method creates a List of the same length based on the length of the array, and then converts the elements of the array into binary and adds them to the List using the collections.addall () method. This is the most efficient way. Key code:

ArrayList< String> arrayList = new ArrayList<String>(strArray.length);
Collections.addAll(arrayList, strArray);
Copy the code

Testing:

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

Result: Also successfully append an element “1”.

[null.null.1]
Copy the code

Application scenario: After an array is converted to a List, add, delete, modify, and check the List. If the List has a large amount of data, use the List first to improve the operation speed. Note: Attach the source code for the 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 and c.dd (element) operate in bitwise or, and then assign to result
    return result;
}
Copy the code

Problem solving

Question: If the array type is an integer array, will an error be reported when converting to a List? Answer: In a JDK1.8 environment, these three conversions work fine. Use at ease. The test results for converting an Integer[] array to a List are as follows: Method 1: Add or delete is not supported

Integer[] intArray1 = new Integer[2];
List<Integer> list1 = Arrays.asList(intArray1);
System.out.println(list1);
Copy the code

Running result:

[null.null]
Copy the code
  1. Method 2: Add or delete
Integer[] intArray2 = new Integer[2];
List<Integer> list2 = new ArrayList<Integer>(Arrays.asList(intArray2)) ;
list2.add(2);
System.out.println(list2);
Copy the code

Running result:

[null.null.2]
Copy the code
  1. Method 3: Supports adding and deleting data and has the most efficient data volume
Integer[] intArray3 = new Integer[2];
List<Integer> list3 = new ArrayList<Integer>(intArray3.length);
Collections.addAll(list3, intArray3);
list3.add(3);
System.out.println(list3);
Copy the code

Running result:

[null.null.3]
Copy the code

The correct way to translate an Integer[] array into a List is as follows. Error prone: Possible errors might be converted like this:

int[] intArray1 = new int[2];
List<Integer> list1 = Arrays.asList(intArray1);// Error here!!
Copy the code

Error cause: The types of both sides of the equal sign are inconsistent, of course, the compilation failed. See below for an analysis. Int [] or Integer[] is the correct way to declare an array. Answer: Only Integer[] can be used to convert List, that is, only the wrapper type of the basic data type can be directly converted to List. Wechat search public number inverse front start pen, after attention to reply programming resources, get a variety of classical learning materials.

Here’s why: Let’s look at the definition of List in the Java source code (don’t be afraid to read the source code, see my analysis, very easy to understand) :

public interface List<E> extends Collection<E> {omitted... }Copy the code

Look at the Java source definition of Arrays.aslist () :

public static <T> List<T> asList(T... a) {
    return new ArrayList<>(a);
}
Copy the code
  • As you can see from the source code above, when you declare a List, you need to pass a generic type as a parameter, and the asList() parameter type is also a wildcard type in generics. All generics in Java must be reference types.
  • What is a reference type? If an Integer is a reference type, what type is an int? Int is a basic data type, not a reference type. This is why there is no List in Java, only List.
  • Byte, short, int, long, float, double, and char are not reference types, so none of them can be used as a parameter to List. But String, array, class, and interface are reference types that can be used as parameters to List, so there is a collection of List interface types, a collection of List

    array types, and a collection of List classes. But there are no collections of basic types such as list and list.
    []>

With that in mind, let’s look at why the second line of code compiles, but the third line compiles with an error.

int[] intArray1 = new int[1]; 
Arrays.asList(intArray1);// Compile without error
List<Integer> list1 = Arrays.asList( intArray1);// Compile error
Copy the code

The answer:

  • In the second line of code, the input to the arrays.aslist () method is a reference int[], so the return value must be of type List

    . The full code for this is: List

    intsArray = Arrays.aslist (intArray1); , so the compilation passed, no problem.
    []>
    []>
  • List

    = List

    = List
    []>
    []>
    []>

conclusion

Now you can see why int[] is not directly converted to List, whereas Integer[] is. Since the generic type in List must be a reference type, int is a basic data type, not a reference type, but the wrapper type of int, Integer, is a class type and is a reference type, Integer can be used as a parameter to List. List can exist in Java, but there is no List type. When coding, we need to know not only how, but also why. By analyzing the SOURCE code of the JDK, we can get first-hand information, not only about how to use it, but also about why.