Talking about the use of Arrays.asList() method

Talking about the use of Arrays.asList() method

 

 

 First, the method converts the array to a list. There are a few things to note:

  (1) This method is not applicable to basic data types (byte, short, int, long, float, double, boolean)

  (2) The method links the array with the list, when one of them is updated, the other is automatically updated

  (3) The add and remove methods are not supported.

In the java language, a very convenient way to convert an array into a List collection is List<String> list = Arrays.asList("a","b","c");

But you may not know that the length of the List obtained in this way cannot be changed. When you add or remove an element to this List (eg list.add("d");) the program throws an exception (java.lang.UnsupportedOperationException). How could this be? ! Just look at how the asList() method is implemented.

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

When you see this code, you may think that there is no problem, isn't it just returning an ArrayList object? The problem lies here. This ArrayList is not under the java.util package, but java.util.Arrays.ArrayList, which is obviously an inner class defined by the Arrays class itself! This inner class does not implement add(), remove() methods, but directly uses the corresponding methods of its parent class AbstractList. And add() and remove() in AbstractList directly throw java.lang.UnsupportedOperationException!

To sum up, if your List is only used for traversal, use Arrays.asList()! If you want to add or delete elements to your List, just obediently create a new java.util.ArrayList and add elements one by one!

Guess you like

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