Whenever you have a primitive array and you would like to convert it to List
(collection-based array). You might do this using asList() method of Arrays
class of Collections framework. But this doesn't result to ArrayList
, instead to an implementation of List with added feature of not being resizable, and still honoring all of the other methods in the interface.
Let's demonstrate by an example:
1: String[] array = {"Cat", "Dog"}; // [Cat, Dog]
2: List<String> list = Arrays.asList(array); // returns fixed size list
3: list.set(1, "Lion"); // [Cat, Lion]
4: array[0] = "Fox"; // [Fox, Lion]
5: String[] array2 = (String[]) list.toArray(); // [Fox, Lion]
6: list.remove(1); // throws UnsupportedOperationException
Line 3 and 4 show that you can change elements in either array or the list.
Line 6 shows that list is not resizable, because it is backed by the underlying array.
That's all for this InfoSnippet.
Let me know if you have questions.