I'm trying to set a List
unmodifiable.
In my code, I have a method which returns a list.
This list shouldn't be modified, but I don't want to catch the exception returned by the unmodifiableList.
private List<T> listeReferenceSelectAll = null;
List<T> oListeRet = new ArrayList<T>();
oListeRet = listeReferenceSelectAll;
return new ArrayList<T>(oListeRet);
It is an existing code and I have to transform it to return an unmodifiable list, but if an "add" method has been called, no exception has to be caught.
First I have create a class which implements List to override "add" method to log the exception and not to catch it.
But I don't know how to correctly instantiate it...
The unmodifiableList() method of java. util. Collections class is used to return an unmodifiable view of the specified list. This method allows modules to provide users with “read-only” access to internal lists.
The unmodifiable view of the specified ArrayList can be obtained by using the method java. util. Collections. unmodifiableList().
The solution to this problem is quite simple and is highlighted in the following code. final List<String> modifiable = new ArrayList<>(); modifiable. add("Java"); modifiable. add("is"); // Here we are creating a new array list final List<String> unmodifiable = Collections.
Java Collections unmodifiableList() Method The unmodifiableList() method of Java Collections class is used to get an unmodifiable view of the specified list. If any attempt occurs to modify the returned list whether direct or via its iterator, results in an UnsupportedOperationException.
Collections.unmodifiableList
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. The returned list will be serializable if the specified list is serializable. Similarly, the returned list will implement RandomAccess if the specified list does.
You need java.util.Collections
:
return Collections.unmodifiableList(oListeRet);
If you have to write your own, have that class implement the List
interface and throw exceptions for the methods that modify contents.
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