What is the difference between
Collection c = new ArrayList();
And
ArrayList c = new ArrayList();
They seem to be both of type ArrayList and thus able to invoke the same methods.
What is the difference between
Collection c = new ArrayList();
And
ArrayList c = new ArrayList();
They seem to be both of type ArrayList and thus able to invoke the same methods.
In the second case you can call methods on c
that are specific to ArrayList
as c
is declared as type ArrayList
.
In the first case, you can only call methods that are defined for Collection
(and must also be in ArrayList
).
For example, ArrayList
declares functions that use indexes (such as get
and indexOf
) but Collection does not have them.
A Collection
is an interface that defines the highest-level of shared collection behavior, and extends Iterable
(which just defines the iterator()
method).
A List
is an interface that defines the highest-level of shared List
behavior.
ArrayList
is an implementation of List and in general wouldn't be used in a declaration unless you need an implementation guarantee (e.g., fast indexed access), but is fine to use as a list value.
Read the docs to see the differences–they're described in the API. The implementation (ArrayList
) will have a type-specific implementation of each method in each interface it implements.