• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Tim Cooke
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Devaka Cooray
  • Ron McLeod
  • paul wheaton
Saloon Keepers:
  • Tim Moores
  • Piet Souris
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Frits Walraven
  • Scott Selikoff

List & ArrayList

 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hello.
I want to know what's the difference between
List<String> test = new ArrayList<String>();
and
ArrayList<String> test = new ArrayList<String>();

thank you.
 
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by storm zcm:
hello.
I want to know what's the difference between
List<String> test = new ArrayList<String>();
and
ArrayList<String> test = new ArrayList<String>();

thank you.



Case #1
That is polymorphic assignment: test is the reference variable of the interface List that refers to the object of the class ArrayList that implements List interface.

Using list interface you are only able to call methods that are declared in the interface List; this is sometimes called narrowing the scope, but good to avail the methods polymorphically.

Case #2
Reference variable of class ArrayList refers to the object of the its class.
So using the reference variable you can call all the methods that are available with that class including implemented methods of the List interface.

In both the cases we have type safe list, the List can only contain String objects, nothing else. Or in other words the add() method will only accept String object.
 
Cao Bin
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you.
I get it.
 
Willie Smits can speak 40 languages. This tiny ad can speak only one:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic