3

In most of the Java code that uses collections,i see something like this.

List<String> list = new ArrayList<String>(); 

But i always wondered why it is preferred over

ArrayList<String> = new ArrayList<String>();

I researched a bit but wasnt able to understand a lot.

Anusha Pachunuri
  • 1,389
  • 4
  • 18
  • 39

3 Answers3

10

Because when using the object by its interface you can later change the implementation. For example:

public ArrayList<String> doSomething(..) {
    ...
    return arrayList;
}

But after a while it appears ArrayList is inefficient for what it is mostly used by the callers of this method, so you decide to change it to LinkedList.

  • if your method returns just List you are done
  • if your method returns ArrayList you should go to all places that the method is invoked and change that. And what if someone used some arraylist-specific methods - you have to think how to refactor that. And that's the good scenario. If your code is a library and other branches/companies are using it you may be stuck with the inefficient code.

See also:

Community
  • 1
  • 1
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • 2
    A general rule of thumb is to use a type that's as specific as you need -- and no more. So if you need LinkedList-specific methods, type it to LinkedList instead of List; and if you don't need any List-specific methods, you may be better typing it to Collection instead of List. – yshavit Dec 05 '11 at 07:15
  • Is that not contradicting the above statement? – Anusha Pachunuri Dec 05 '11 at 07:17
  • 1
    Not really, no. Most of the time, you don't need the implementation-specific methods, so you're better off just declaring it as a List. LinkedList, for instance, combines several interfaces, so if you need to use them all, you could be justified in declaring a LinkedList. On the other hand, if you don't even need to call get/set, but only ever need an iterator, declaring it as a Collection or even Iterable may be better. – yshavit Dec 05 '11 at 07:24
2

Hi here are the benefits of using interface object

http://artofsoftwarereuse.com/2010/04/24/5-advantages-of-using-interfaces-for-reusable-assets/

Hemant Metalia
  • 29,730
  • 18
  • 72
  • 91
1

Given that Java is a strongly-typed language it is always considered best-practice to program against interfaces (within reason, of course). Doing so allows you to swap out implementations later with little effort.

This is especially true for method parameters as it does not tie you to a specific implementation. Perhaps you use ArrayList in one case but you use a LinkedList elsewhere.

Jim Mitchener
  • 8,835
  • 7
  • 40
  • 56