• 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
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
  • paul wheaton
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Henry Wong
Saloon Keepers:
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Tim Moores
  • Mikalai Zaikin
Bartenders:
  • Frits Walraven

need for UPCAST

 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Dear Members :

Could you please let me know the difference each of the following declarations will make ?

Collection xList = new ArrayList(); ---- 1
List xList = new ArrayList(); ---------- 2
ArrayList xList = new ArrayList();------ 3

I am ignoring the 1.5 way of declaration ie; ArrayList<Item> itemsList = new ArrayList<Item>();

What I am trying to understand - what advantage/disadvantage I will get
in declaring above ways (1-3) ?

Thanks in advance.
Atanu
 
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
1. Without casting, you will only be able to call methods from the Collection interface on the object that xList references. So even though xList refers to an ArrayList instance, you would not be able to call the indexOf method for example. The advantage of declaring it this way is that it makes it easy to replace the ArrayList with any other object that implements the Collection interface.

2. Same as 1 except replace Collection with List and indexOf with some method that is not in the List interface (e.g. trimToSize)

3. This allows you to use all of ArrayList's methods, but could cause problems if you decide you want to use some other type of List/Collection in future.
 
Atanu Banerjee
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Joanne :

Thanks very much - got it what you say.

Atanu
 
Beauty is in the eye of the tiny ad.
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic