Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it acceptable to return unmodifiableList or should I return array?

I have method List<Foo> getFoos () which gets the data from remote server and returns it.

Of course, user shouldn't change number of items of the list because he'll get data not synchronized with data on the server (and if he want change number of items he has special methods like addFoo ()).

First approach was to return array and change method's signature to Foo[] getFoos (). But it's more common in java and more convenient to user to operate with collections so I changed signature to List<Foo> getFoos (). This method always returns

Collections.unmodifiableList (originalList)

So, when user try to change the list he will get RuntimeException.

Are there any recommendations about api design in similar cases?

like image 627
Roman Avatar asked Feb 02 '10 17:02

Roman


People also ask

Does unmodifiableList create a new list?

You are creating new lists that are modifiable, with the elements from unmodifiable (immutable) lists, and then modifying the (mutable) lists.

Are arrays asList Unmodifiable?

When we create a list from an array using java. util. Arrays. asList() , the list is immutable.

Can you modify the collection return by arrays asList ()? If no why?

Arrays. asList() method returns a fixed-size list backed by the specified array. Since an array cannot be structurally modified, it is impossible to add elements to the list or remove elements from it.

What is collections unmodifiableList?

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 is perfectly acceptable and should be faster (no need to create an array).

Edit - In terms of API design, you should just make your JavaDoc clear! People who use a method without reading its doc deserve the surprise :p

like image 176
deubeulyou Avatar answered Oct 29 '22 10:10

deubeulyou


I'd also say it is perfectly acceptable and much better than returning an array (which some suggest should be treated as a deprecated type altogether). If you want to be more explicit about it in the API however, you could consider returning an ImmutableList from Google Collections.

like image 38
Fabian Steeg Avatar answered Oct 29 '22 09:10

Fabian Steeg