This method returns a fixed-size list backed by the specified array.
Changes to the source array reflect to the List and changes to the List reflect to the source array.
package com.logicbig.example.arrays;
import java.util.Arrays;
import java.util.List;
public class AsListExample3 {
public static void main(String... args) {
String[] stringArray = {"one", "two", "three"};
List<String> list = Arrays.asList(stringArray);
System.out.println(list);
stringArray[0] = null;
System.out.println(list);
list.set(2, "last");
System.out.println(Arrays.toString(stringArray));
}
}
Output
[one, two, three]
[null, two, three]
[null, two, last]
Cannot add more elements to the List as it is fixed size.
package com.logicbig.example.arrays;
import java.util.Arrays;
import java.util.List;
public class AsListExample4 {
public static void main(String... args) {
String[] stringArray = {"one", "two", "three"};
List<String> list = Arrays.asList(stringArray);
list.add("four");
}
}
Output
Caused by: java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java:148)
at java.util.AbstractList.add(AbstractList.java:108)
at com.logicbig.example.arrays.AsListExample4.main(AsListExample4.java:17)
... 6 more