Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList vs the List returned by Arrays.asList() [duplicate]

Tags:

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.

like image 273
Roam Avatar asked Sep 08 '14 17:09

Roam


1 Answers

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.

like image 151
SparkOn Avatar answered Oct 13 '22 02:10

SparkOn