Assuming you have a class something like:
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 it ever appropriate for declarations to specify the concrete class e.g. ArrayList instead of the List interface? If so, when?
Edit> This question has nothing to do with when to use a LinkedList and when to use an ArrayList. That is a separate question that is answered elsewhere. The question is about when declarations should be the interface (List) for clarity and when it should specify an implementation e.g. ArrayList because it matters given what the method is going to do or how the instance variable will be leveraged.
Normally you should only use the interface List
to declare your structure. However, on the rare occasion you need to use a specific method that is only available for a certain implementation of List
such as LinkedList
or ArrayList
then you should declare your list type explicitly. However, this limits flexibility and should be done sparingly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With