Say I create a method that does something with an ArrayList
:
public int sum(ArrayList<Integer> list){
int sum = 0;
for(Integer x : list){
sum += x;
}
return sum;
}
That will work fine for now, and anybody with an ArrayList
can call it. But what about people with a LinkedList
? They're out of luck!
But why should I exclude them? My function doesn't actually use anything specific to ArrayList
- I don't actually care or need to know what type of List
the function is being given. So why not make it as general as possible, so anybody with a List
can call my function?
public int sum(List<Integer> list){
int sum = 0;
for(Integer x : list){
sum += x;
}
return sum;
}
Similarly, why should I declare a variable as an ArrayList
if I don't actually care what type of List
it is? What if I want to change that variable to a LinkedList
later? If I declare it as a List
, then that's a one-line change. But if I declared it as an ArrayList
, then I have to change every single reference to it. That can become very annoying in larger projects, so it's usually better to keep your variables as general as possible.