Why can't Arrays.asList (T ... a) be add or remove?

(This article is a multipost with Go to the horizon)

When I google about the method ʻArrays.asList (T ... a), it is often written that "The List returned by this method cannot be ʻadd or remove, so be careful. " I am. However, there is often no mention of "why can't you?", So I'll explain why.

In a nutshell, "because it's for ** wrapping ** an array so that it can be treated as a List "</ font>. (It's not something to convert)

How do you use it in the first place?

Use this when you want to treat an array as List <T>.

For example, I have a method that takes a List as an argumentCollections.shuffle (List <?> List)to shuffle, but there is no method that takes an array as an argument. In such a case, you can pass an array as an argument by wrapping it like Collections.shuffle (Arrays.asList (a)).

Since the list returned by ʻArrays.asList (T ... a)is linked to the original array, rewriting the elements of thisList` will also rewrite the elements of the array.

String[] array = new String[] {
    "aaa", "bbb", "ccc", "ddd", "eee"
};

//Wrap the array in a List and shuffle it
Collections.shuffle(Arrays.asList(array));

//The original array is shuffled properly
// => [ccc, eee, ddd, bbb, aaa]
System.out.println(Arrays.toString(array));

If you look at the implementation of the list class returned by ʻArrays.asList (T ... a)`, you'll see that it's just wrapping an array. [^ ArrayList]

[^ ArrayList]: This ʻArrayListis a separate class fromjava.util.ArrayList`.

java:Array.asList(T...)Implementation of the list returned by (excerpt)


private static class ArrayList<E> extends AbstractList<E>
    implements RandomAccess, java.io.Serializable
{
    private final E[] a;

    ArrayList(E[] array) {
        a = Objects.requireNonNull(array);
    }

    @Override
    public int size() {
        return a.length;
    }

    @Override
    public E get(int index) {
        return a[index];
    }

Why can't I add or remove?

If you try to implement ʻaddorremove`, you need to change the length of the underlying array. However, Java does not allow you to change the length of the array.

Therefore, methods that operate on the contents of the array, such as set and get, are implemented, but methods that require modification of the array itself, such as ʻadd and remove`, are implemented. I haven't. [^ imp]

[^ imp]: To be precise, the List interface needs to implement ʻadd and remove, so there is a method but it throws ʻUnsupportedOperationException).

Summary

Tomorrow's Java Advent Calendar is in charge of null. who! write! !! !!

** Addendum: ** @ opengl-8080 wrote it! Control log output with Doma2 --Qiita

Recommended Posts

Why can't Arrays.asList (T ... a) be add or remove?
[Bootstrap] Suddenly I can't log out ~ Why? It seems to be a CSRF problem ~