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.
Who is Participating?
sciuriwareConnect With a Mentor Commented:
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.

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.
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.

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?
Asheesh_KumarAuthor Commented:
satisfactory solution.
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.