Hi ~ everyone have a nice weekend, I am A Java programmer, recently in the work, that is, no bug to change, there is no demand, and can not let the boss see themselves in the fish, boring I began CTRL + mouse left key, aimlessly looking at the JDK source code in front of. Today I’m going to share some of the pitfalls I’ve encountered with Java.util. Arrays.

The three problems are analyzed and the solutions are given

  1. The List of fixed heroes returned by asList does not support adding elements
  2. Changes to the original array will affect the List that we get
  3. You cannot directly convert Arrays of primitive types using arrays. asList

Allow me to start today with the JDK source code written by James Gosling, the father of Giant Java.

The List of fixed heroes returned by asList does not support adding elements

code

public static void main(String[] args) {
        String[] arr = new String[]{"aa", "bb"};
        List<String> list = Arrays.asList(arr);
        list.add("cc");
    }

The 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 Test.main(Test.java:8)

Reason is Java. Util. Arrays. The ArrayList class implements the set (), the get (), the contains () method, but did not achieve increase element method (in fact is you can call the add method, but there is no specific implementation, Just throw UnsupportedOperationException exception), so its size is fixed. The value can be set using the set method, and the default length is 10.

The solution

Create an ArrayList

Code:

public static void main(String[] args) {
        String[] arr = {"aa", "bb", "cc"};
        List<String> list = Arrays.asList(arr);
        ArrayList<String> strings = new ArrayList<>(list);
        strings.add("dd");
        System.out.println(strings.toString());
    }

Execution Result:

[aa, bb, cc, dd]

Through the collections.addall () method of the Collections utility class (most efficient, recommended)

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 to binary using the collections.addall () method. And then add it to the List, which is the most efficient way.

Code:

public static void main(String[] args) {
        String[] arr = {"aa", "bb", "cc"};
        ArrayList<String> strings = new ArrayList<>(arr.length);
        Collections.addAll(strings, arr);
        strings.add("dd");
        System.out.println(strings.toString());
    }

Execution Result:

[aa, bb, cc, dd]

Elegant way to write Stream

Code:

public static void main(String[] args) {
        String[] arr = {"aa", "bb", "cc"};
        List<String> list = Stream.of(arr).collect(Collectors.toList());
        list.add("dd");
        System.out.println(list.toString());
    }

Execution effect:

[aa, bb, cc, dd]

The underlying method of converting an array to a stream and then using addAll() is less efficient than the collections.addall () method, but elegant.

Changes to the original array will affect the List that we get

code

 public static void main(String[] args) {
        String[] arr = {"aa", "bb", "cc"};
        List<String> list = Arrays.asList(arr);
        arr[1] = "dd";
        System.out.printf("arr:%s list:%s", Arrays.toString(arr), list);
    }

The execution result

arr:[aa, dd, cc] list:[aa, dd, cc]

The reason is that ArrayList, the internal class of Arrays, actually directly uses the original array and hands the List obtained through Arrays.asList to other methods for processing, which is easy to cause bugs due to shared Arrays and mutual modification.

You cannot directly convert Arrays of primitive types using arrays. asList

code

public static void main(String[] args) {
        int[] arr = {1, 2, 3};
        List list = Arrays.asList(arr);
        System.out.println(list.size());
    }

The execution result

1

The reason for this is that the argument to the asList method must be an object or an array of objects, and the native data type is not an object. When passed an array of the native data type, the real argument to the asList method is not the elements of the array, but the array object itself.

The solution

Java8 converts three basic types of arrays into lists via stream

If the JDK version is later than 1.8, you can use stream to quickly convert the following three types of arrays: int[], long[], and double[]. Other types, such as short[], byte[], and char[], are not supported in JDK1.8.

Code:

public static void main(String[] args) {
        int[] arr = {1, 2, 3};
        List<Integer> list = Arrays.stream(arr).boxed().collect(Collectors.toList());
        System.out.println(list);
    }

Execution effect:

[1, 2, 3]

I am Zhuang, a back-end programmer, wechat search: science and technology cat, continue to share original programming technology, practical software, science and technology information, we next period