trozen :
Which one is the recommended approach:
private final List<Object> list = new ArrayList<>();
public List<Object> getListView() {
return Collections.unmodifiableList(list);
}
or
private final List<Object> list = new ArrayList<>();
private final List<Object> listView = Collections.unmodifiableList(list);
public List<Object> getListView() {
return listView;
}
The latter saves on object creation, but is it worth the effort?
Mureinik :
Creating an unmodifiableList
is an O(1) operation (essentially, it instantiates a java.util.Collections$UnmodifiableList
and assings your list to a datamember).
Unless you have a very convincing benchmark of your special-case that shows the contrary, it probably just isn't worth the hassle of caching it.