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.
Asheesh_KumarAsked:
Who is Participating?
 
sciuriwareConnect With a Mentor Commented:
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
 
WoodzConnect With a Mentor Commented:
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
 
sciuriwareConnect With a Mentor Commented:
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
 
Asheesh_KumarAuthor Commented:
satisfactory solution.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.