简体   繁体   中英

Arrays.asList() in java returned refrence list to souce Array?

After executing below code, I feel Arrays.asList returned reference to source array thats y after printing it showing the final content from source array.

String[] circus2 = { "Monkey", "Elephant" };
List<String> zoo2 = Arrays.asList(circus2);
circus2[1] = "bear";
System.out.println("zoo2 size: " + zoo2.size());
System.out.println("zoo2 : " + zoo2);

====

zoo2 size:2
zoo2 : [Monkey, bear]

Please advice me, if im wrong. Java Document says it returned "Returns a fixed-size list backed by the specified array.".

What the doc actually means is once you convert the array to a list, you can modify only the existing contents of the list (ie, the array behind it) but not add / remove elements.

public static void main(String[] args) {
    String[] str = new String[2];
    str[0] = "abc";
    str[1] = "def";
    List<String> l = Arrays.asList(str);
    l.set(0, "ghi");

    for (String s : str) {
        System.out.println(s);
    }
}

O/P :

ghi
def

But if you try l.add("ppp"); then you will get an error. Why? - because the List returned by Arrays.aslist() is a static inner class in Arrays class (it is not java.util.ArrayList ), so, you will get UnsupportedOperationException as certain methods which should be overridden by definition are not actually overridden in the static inner class.

As api doc says, Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.) Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.)

It is like, the source array holds the elements, the list is a kind of view, if you have updated the source array, the list reads the updated value. And if you update the element in the list, the element would be changed in the array too.

Note that, internally, the returned ArrayList is not java.util.ArrayList , it is an inner class ArrayList in Arrays class.

The list is indeed backed by the array. If you change the array, the list is changed:

String[] array = new String[] { "a", "b", "c" };
List<String> list = Arrays.asList(array);
array[0] = "asdf";
System.out.println(list.get(0)); // prints "asdf"

This also works the other way around:

String[] array = new String[] { "a", "b", "c" };
List<String> list = Arrays.asList(array);
list.set(0, "asdf");
System.out.println(array[0]); // prints "asdf"

However, you cannot change the size of the list. You can try it yourself. The following code throws an java.lang.UnsupportedOperationException:

String[] array = new String[] { "a", "b", "c" };
List<String> list = Arrays.asList(array);
list.add("asdf");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM