Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between ArrayList<Integer> list = new ArrayList<Integer>(); and Collection<Integer> list1 = new ArrayList<Integer>();

Tags:

java

I don't understand difference between:

  1. ArrayList<Integer> list = new ArrayList<Integer>();
  2. 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?

like image 561
Mikky Avatar asked Dec 03 '22 00:12

Mikky


1 Answers

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
    }
}
like image 174
gd1 Avatar answered May 24 '23 21:05

gd1