What are some of the ways to make an ArrayList
read-only other than Collections.unmodifiableList()
?
-
1possible duplicate of make ArrayList Read only– austin wernliJul 29, 2015 at 16:06
-
2@austinwernli It's not a duplicate. Read the question again.– Suresh AttaJul 29, 2015 at 16:07
-
@sᴜʀᴇsʜᴀᴛᴛᴀ seems to be very similar.– austin wernliJul 29, 2015 at 16:10
-
This was asked to me while a job interview. Although I explained to him that it could be done by extending the arraylist class. The interviewer was not convinced.– Abhishek SinghJul 29, 2015 at 16:14
-
1Maybe because the conclusion should have been : it is indeed possible, but in real world application I would use what JDK has, because it already meets the requirement and has been extensively tested– Serge BallestaJul 29, 2015 at 16:18
3 Answers
The most direct way would be to create a wrapper class, implementing an List but explicitely returning UnsupportedOperationException for all methods modifying the list. You could just extend AbstractList to have this with less code from you.
And you will obtain a clone of what Collections.unmodifiableList would have given you for free... Doc says : Returns an unmodifiable view of the specified list. This method allows modules to provide users with "read-only" access to internal lists. Query operations on the returned list "read through" to the specified list, and attempts to modify the returned list, whether direct or via its iterator, result in an UnsupportedOperationException, but less tested so with a higher risk of silent bugs.
My advice is: if it exists, and if it meets your requirements, use it and do not reinvent it.
Extend the array list class and re-implement the methods that change the list to not change the list.
You could also make it final if you know the values ahead of time.
Why would you re-invent the wheel?
-
If you can't reinvent something, how can you invent something new? Jul 29, 2015 at 16:12
There is no (practical) way to make an ArrayList
read only. Wrapping with Collections.unmodifiableList
creates a new object which is read only. The original ArrayList
is still mutable.
If you want to build a List
which is immutable, use guava's ImmutableList
.
-
So what will happen if I make change to original list? Will changes be made to returned immutable list too ? Jul 29, 2015 at 16:16
-
From the javadoc of immutable list: Despite the method name, this method attempts to avoid actually copying the data when it is safe to do so. The exact circumstances under which a copy will or will not be performed are undocumented and subject to change. Jul 29, 2015 at 16:20
-
A look at the source code shows that there is special handling when copyOf is called with another ImmutableCollection. Otherwise, a copy of the data is created. Jul 29, 2015 at 17:44