Re: Diff. between List<Object> and ArrayList<Object>? usage samples?
On Oct 27, 12:52 pm, g...@osgitest.org (Gianni Galore) wrote:
I want to define a list of objects. As far as I know one can implement it=
as
List<Object mylist = new .....
or
ArrayList<Object> mylist = new ....
What is the difference?
The difference is that the approach can use any 'List' implementation,
such as 'ArrayList', 'TreeList',
'java.util.concurrent.CopyOnWriteArrayList' and so on. The second
approach only allows 'ArrayList' and its subtypes.
That means, for example, that given
ArrayList <Foo> mutableFoos = new ArrayList <Foo> ();
you cannot declare
ArrayList <Foo> immutableFoos =
Collections.unmodifiableList( mutableFoos );
but you can declare
List <Foo> immutableFoos =
Collections.unmodifiableList( mutableFoos );
You should declare variables and method return types to be the widest
applicable type (but no wider). So usually you'll prefer
List <Foo> var = new AnyList <Foo> ();
over
ArrayList <Foo> var = new ArrayList <Foo> ();
See Josh Bloch's book /Effective Java/ for details on some of this.
<http://java.sun.com/docs/books/effective/>
Item 52, "Refer to objects by their interfaces"
Item 18, "Prefer interfaces to abstract classes"
Item 19, "Use interfaces only to define types"
Item 53, "Prefer interfaces to reflection"
Own this book. Study this book. Reread this book frequently.
--
Lew