Java – is it correct to use ArrayList or LinkedList instead of list when declaring variables / parameters?
See English answers > type list vs type ArrayList in Java 15
public class foo { private List<String> fooThings; public void doSomething(List<String> things) { // Do a bunch of things here // Possibly setting fooThings at some point as well } }
Is the declaration appropriate to specify a specific class, such as ArrayList instead of the list interface? If so, when?
Edit > this question has nothing to do with when to use LinkedList and when to use ArrayList This is a separate question that has been answered elsewhere The problem is about when to declare an interface (list) so that it is clear and when to specify an implementation, such as ArrayList, because it is important what a given method will do or how to use instance variables
Solution
In general, you should only use the interface list to declare your structure However, in rare cases where you need to use a specific method (such as LinkedList or ArrayList) that only applies to an implementation of list, you should explicitly declare the list type However, this limits flexibility and should be carried out with caution