Type List vs type ArrayList in Java

kji picture kji · Feb 17, 2010 · Viewed 414k times · Source
(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.)

Answer

kgiannakakis picture kgiannakakis · Feb 17, 2010

Almost always List is preferred over ArrayList because, for instance, List can be translated into a LinkedList without affecting the rest of the codebase.

If one used ArrayList instead of List, it's hard to change the ArrayList implementation into a LinkedList one because ArrayList specific methods have been used in the codebase that would also require restructuring.

You can read about the List implementations here.

You may start with an ArrayList, but soon after discover that another implementation is the more appropriate choice.