I don't understand difference between:
ArrayList<Integer> list = new ArrayList<Integer>();
Collection<Integer> list1 = new ArrayList<Integer>();
Class ArrayList
extends class which implements interface Collection
, so Class ArrayList
implements Collection
interface. Maybe list1
allows us to use static methods from the Collection
interface?
An interface has no static methods [in Java 7]. list1
allows to access only the methods in Collection
, whereas list
allows to access all the methods in ArrayList
.
It is preferable to declare a variable with its least specific possible type. So, for example, if you change ArrayList
into LinkedList
or HashSet
for any reason, you don't have to refactor large portions of the code (for example, client classes).
Imagine you have something like this (just for illustrational purposes, not compilable):
class CustomerProvider {
public LinkedList<Customer> getAllCustomersInCity(City city) {
// retrieve and return all customers for that city
}
}
and you later decide to implement it returning a HashSet
. Maybe there is some client class that relies on the fact that you return a LinkedList
, and calls methods that HashSet
doesn't have (e.g. LinkedList.getFirst()
).
That's why you better do like this:
class CustomerProvider {
public Collection<Customer> getAllCustomersInCity(City city) {
// retrieve and return all customers for that city
}
}
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