To emphasize what Oliver Charlworth said in a comment: The most important difference is whether this information is public or not.
From how the question is written, it looks like you are talking about a field (not a method parameter or return value). And a private field, by definition, is an implementation detail, and you can make it arbitrary. Thus, it would be possible to declare it as an ArrayList
, although, strictly speaking, it does not matter. To put it this way: you said
if someone ... changed list
to LinkedList
, that would be problematic ...
Anyone who can change an ad from
private List<T> list = new ArrayList<T>();
to
private List<T> list = new LinkedList<T>();
can also change an ad from
private ArrayList<T> list = new ArrayList<T>();
to
private LinkedList<T> list = new LinkedList<T>();
The only practical way to prevent this is to add this (important) implementation detail as a comment, for example.
private final List<T> list = new ArrayList<T>();
(This can also be implemented by internally transferring the list to a method that expects it to be RandomAccess
. This was suggested by AlexR but referenced to public
methods. For private
methods, this even won the βprevent anyone from changing the method signature if intent and reason for the requirements of RandomAccess
not documented).
source share