0

So far from most the related posts i have understood difference in usage between ArrayList assigned to List ,and ArrayList assigned to ArrayList

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

And as a matter of fact the preferred methodology is "Programming to Interface"

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

But my question is

  • Does the List object considered/becomes an ArrayList Object (ones ArrayList obj is assigned) ?

    or

  • Does it remains the same as a List Object?

Thanks for the reply in advance..

Community
  • 1
  • 1

3 Answers3

1

List never become a class and it's an interface.

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

In that above case List is holding a reference to the implemented Class ArrayListof it's type with a name given arrName .

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
1

References are like glasses. If you wear green coloured glasses, the world looks green, if you wear blue coloured glasses, the world looks blue. The world remains the same. Only how you see it changes

Similarly, if you have an ArrayList instance and a reference to it, if you want to call methods that are present only in List that are overriden by ArrayList, then use : List<T> x = new ArrayList<>().

*If you want to call only methods of ArrayList, then use ArrayList<T> = new ArrayList<>.

The second approach should be used because the right method of the right kind of List is always called. You can pass any List instance around by coding to the reference.

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
0

Does the List object considered/becomes an ArrayList Object (ones ArrayList obj is assigned) ?

List arrName is a reference which is pointing to object of its implemented class ArrayList.

Does it remains the same as a List Object?

List is an interface so you can not declare List object. It will remain object of ArrayList only. Just to point out, as the reference is of List so you can only call methods declared in List interface (which will call its implementation in ArrayList).

Naman Gala
  • 4,670
  • 1
  • 21
  • 55