(1) List<?> myList = new ArrayList<?>();
(2) ArrayList<?> myList = new ArrayList<?>();
I understand that with (1), implementations of the List interface can be swapped. It seems that (1) is typically used in an application regardless of need (myself I always use this).
I am wondering if anyone uses (2)?
Also, how often (and can I please get an example) does the situation actually require using (1) over (2) (i.e. where (2) wouldn't suffice..aside coding to interfaces and best practices etc.)
(3) Collection myCollection = new ArrayList();
I am using this typically. And only if I need List methods, I will use List. Same with ArrayList. You always can switch to more "narrow" interface, but you can't switch to more "wide".
The only case that I am aware of where (2) can be better is when using GWT, because it reduces application footprint (not my idea, but the google web toolkit team says so). But for regular java running inside the JVM (1) is probably always better.
List
interface have several different classes -ArrayList
andLinkedList
.LinkedList
is used to create an indexed collections andArrayList
- to create sorted lists. So, you can use any of it in your arguments, but you can allow others developers who use your code, library, etc. to use different types of lists, not only which you use, so, in this methodyou can use it only with
ArrayList
, notLinkedList
, but you can allow to use any ofList
classes on other places where it method is using, it's just your choise, so using an interface can allow it:In this method arguments you can use any of
List
classes which you want to use:CONCLUSION:
Use the interfaces everywhere when it possible, don't restrict you or others to use different methods which they want to use.