• 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.
0
Asheesh_Kumar
Asked:
Asheesh_Kumar
  • 2
  • 2
3 Solutions
 
WoodzCommented:
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.
0
 
sciuriwareCommented:
So, what is ArrayList more than a List.
Well, List is just an Interface.
ArrayList implements List, and:

    Serializable, Cloneable, Iterable, Collection, RandomAccess.

;JOOP!
0
 
Asheesh_KumarAuthor Commented:
Woodz:
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?
0
 
sciuriwareCommented:
Yes, at least .............. if the methods defined by the Interface 'List' are enough for you.

Compare:

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.

;JOOP!
0
 
Asheesh_KumarAuthor Commented:
satisfactory solution.
0

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