You Should Be Aware of This if You Are Using Arrays.asList in Java
Many of us might have used Arrays.asList to create a List with given array, it’s a very short way to create a list. But I bet very few of us know the impact of doing this. So let’s learn from one of my mistakes.
Problem exemplified
Let’s say we have an array of String and we create a list out of it.
String[] students = new String[] {"Ram", "Shyam", "Balram"};
List<String> studentList = Arrays.asList(students);
Now we have studentList
which is a list of student (“Ram”, “Shyam”, “Balram”). Now let’s update our first element of the list to “Ghanshyam”.
studentList.set(0, "Ghanshyam");
Now check both students
and studentList
. Guess what, both got updated, but we only wanted to update the list right?
Now let’s try another thing. Let’s try to add or remove an item from the list
studentList.remove(0);
studentList.add("Mohan");
What do we get? We get an UnsupportedOperationException
exception. We weren’t expecting this right? What happened ?
Why does it happen?
When we do Arrays.asList(array)
it creates a fixed-size list backed by the specified array. We can’t modify it’s length thus adding or removing is not allowed. And also it is not copied or created, it is just view of the same array, so if you update the value of an element in the list it will…