The method Arrays.asList(<T>...A) returns a List representation of A. The returned object here is a List backed by an array, but is not an ArrayList object.
I'm looking for the differences between the object Arrays.asList() returns and an ArrayList object-- a quick source to tell these without diving into the code.
TIA.
When you call Arrays.asList it does not return a java.util.ArrayList. It returns a java.util.Arrays$ArrayList which is a fixed size list backed by the original source array. In other words, it is a view for the array exposed with Java's collection-based APIs.
String[] sourceArr = {"A", "B", "C"}; List<String> list = Arrays.asList(sourceArr); System.out.println(list); // [A, B, C] sourceArr[2] = ""; // changing source array changes the exposed view List System.out.println(list); //[A, B, ] list.set(0, "Z"); // Setting an element within the size of the source array System.out.println(Arrays.toString(sourceArr)); //[Z, B, ] list.set(3, "Z"); // java.lang.ArrayIndexOutOfBoundsException System.out.println(Arrays.toString(sourceArr)); list.add("X"); //java.lang.UnsupportedOperationException list.remove("Z"); //java.lang.UnsupportedOperationException You cannot add elements to it and you cannot remove elements from it. If you try to add or remove elements from them you will get UnsupportedOperationException.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With