• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1899
  • Last Modified:

declarinon of List list = new ArrayList()

why we declare
List list = new ArrayList();

    instead of

ArrayList list = new Arraylist();

what is advantage/difference of these two declaration.
  • 2
  • 2
3 Solutions
java.util.List is an interface, implemented by many different classes (ArrayList, LinkedList, Stack, Vector, etc...), so declaring the variable as type List rather than ArrayList, means that the underlying implementation of the collection can change as required, yet the core functionality (indexing, adding, removing, etc..) is still allowed.

It is advantageous to keep data types as general as possible, so that the underlying implementation details can change (for example, for performance reasons you could decide to move to a stack implementation), with minimum changes to the processing code, that simply navigates over the list and operates on the items within.

As far as I am aware, there are no disadvantages in this scenario for declaring the data type as List instead of ArrayList.
So, what is ArrayList more than a List.
Well, List is just an Interface.
ArrayList implements List, and:

    Serializable, Cloneable, Iterable, Collection, RandomAccess.

Asheesh_KumarAuthor Commented:
you want to say that if we use

List list = new ArrayList()..
instead of ArrayList list = new ArrYList()...

then if in future we want to assign Vector to List so we can do it like
List list = new Vector()...
no need to change/declare a new variable call Vector?
Yes, at least .............. if the methods defined by the Interface 'List' are enough for you.


class Mouse implements Feeding {}
class Squirrel implements Feeding {}
interface Feeding { public void eat(); }

Now, both classes are to contain a method 'eat()'.

Feeding fm = new Mouse();
Feeding fs = new Squirrel();

Squirrel has an additional method jumpFromTreeToTree();

By fm or fs you can only call 'eat()', as Feeding 'knows nothing' about
methods not defined in Feeding.

Asheesh_KumarAuthor Commented:
satisfactory solution.

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now