• Post Reply Bookmark Topic Watch Topic
  • New Topic

need for UPCAST  RSS feed

 
Atanu Banerjee
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • 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
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • 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
  • Quote
  • Report post to moderator
Hi Joanne :

Thanks very much - got it what you say.

Atanu
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!