Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Collection issue

 
rohit shekhar
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



both a and b behaves similarly but what is the difference?
 
Greg Charles
Sheriff
Posts: 2993
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I curious why you titled this thread, "Collection Issue". Do you mean you're most interested in how these cases would be treated by the garbage collector? If so, the answer is, "not at all".

Both a and b are referring to object of the same type, i.e., an ArrayList. However, code using b would have access to the full interface of methods provided by ArrayList and its base classes, while code using a would only have access to the subset of methods defined by the List interface plus defined by java.lang.Object, the common ancestor of all Java classes. If the code needed to call a method from ArrayList on a that wasn't part of List or Object, then it would have to cast a to an ArrayList first.

However, there aren't any methods I can think of that ArrayList adds to the List interface, so that difference is moot. You would have to cast a to an ArrayList to pass it to any method taking an ArrayList parameter, or to return it from a method declaring an ArrayList return value.
 
Salil Vverma
Ranch Hand
Posts: 257
Hibernate Oracle Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey Rhoit,

This is concept of overriding and implementing the interface.
are you trying to figure out when List a = new ArrayList(); should be used and when ArrayList b = new ArrayList(); ?
 
rohit shekhar
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry greg for less appropriate title actually nothing clicked in mind for title so.. Thanks for your reply... Still one doubt, mostly we will use 'a' instead of 'b'. Any advantage?
 
Greg Charles
Sheriff
Posts: 2993
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's always better to program to the interface. That way if you decide to change the implementation, you don't have to change anything else.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic