Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unmodifiable List in java

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...

like image 822
user2346325 Avatar asked May 03 '13 09:05

user2346325


People also ask

What is an unmodifiable list in Java?

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.

How do you make an ArrayList Unmodifiable in Java?

The unmodifiable view of the specified ArrayList can be obtained by using the method java. util. Collections. unmodifiableList().

How do I change Unmodifiable list?

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.

How do you make a list not modifiable in Java?

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.


2 Answers

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.

like image 29
Achintya Jha Avatar answered Sep 21 '22 12:09

Achintya Jha


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.

like image 179
duffymo Avatar answered Sep 20 '22 12:09

duffymo