Unmodifiable List in java

user2346325 picture user2346325 · May 3, 2013 · Viewed 64.4k times · Source

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

Answer

duffymo picture duffymo · May 3, 2013

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.