Three pits of Java Arrays.asList

Keywords: Java

Pit 1, use Array.asList to convert basic type array

Code

@Slf4j
public class ArrayAsListDemo {
    public static void intArrayToList() {

        int[] arr = {1, 2, 3};
        List list = Arrays.asList(arr);
        log.info("list:{} size:{} class:{}", list, list.size(), list.get(0).getClass());
    }
}

Result

list:[[I@78cb5849] size:1 class:class [I

size is 1...

Analysis

asList the first mock exam T is used as a parameter.

 

 

 

The above code is actually equal to

 

 

So the returned list has only one element, an int array, and three elements. As follows.

 log.info(""+ list.get(0).length);//The result is 3

conclusion

You can't use Arrays.asList directly to convert arrays of basic types

Pit 2, the List returned by Arrays.asList does not support adding or deleting

Code

    public static void putAndRemove() {
        String[] arr = {"1", "2", "3"};
        List<String> list = Arrays.asList(arr);
        try {
            list.add("4");

        } catch (UnsupportedOperationException ex) {
            log.info("add failed");
        }

        try {
            list.remove("1");

        } catch (UnsupportedOperationException ex) {
            log.info("remove failed");
        }
    }

Result

add failed
remove failed

Analysis

ArrayList returned by Arrays.asList is the ArrayList inside Array

private static class ArrayList<E> extends AbstractList<E>
        implements RandomAccess, java.io.Serializable

But add and remove inside AbstractList are not implemented, ArrayList is not overridden, and add and remove are not overridden

 

Pit 3, changes to the original array will directly affect the list

Code

    public static void modifyOriginal() {
        String[] arr = {"1", "2", "3"};
        List<String> list = Arrays.asList(arr);
        log.info("list 0 before modify: "+list.get(0));

        arr[0]="aaaaa";

        log.info("list 0 after modify: "+list.get(0));

    }

Result

list 0 before modify: 1
list 0 after modify: aaaaa

Analysis

The array list inside the array generated by asList directly uses the original array, which is probably the reason why the generated list add and remove are not allowed, because this will affect the original value.

Posted by Techbot on Sun, 19 Apr 2020 07:12:09 -0700