Two Laptop Bag*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Collection issue Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Collection issue" Watch "Collection issue" New topic
Author

Collection issue

rohit shekhar
Ranch Hand

Joined: Mar 05, 2010
Posts: 32



both a and b behaves similarly but what is the difference?
Greg Charles
Sheriff

Joined: Oct 01, 2001
Posts: 2849
    
  11

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

Joined: Sep 06, 2009
Posts: 255

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(); ?


Regards
Salil Verma
rohit shekhar
Ranch Hand

Joined: Mar 05, 2010
Posts: 32
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

Joined: Oct 01, 2001
Posts: 2849
    
  11

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.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Collection issue