File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Casting through diffrent tree branches. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Casting through diffrent tree branches." Watch "Casting through diffrent tree branches." New topic

Casting through diffrent tree branches.

John Bateman
Ranch Hand

Joined: Mar 09, 2000
Posts: 320
I have an application that 'used' to send back collections of User objects in an ArrayList. There came a time when the ArrayList was too specific and we had to get more general so we changed our prog to return a Collection. The reason for this was because there were times when we needed a HashSet to guarantee uniqueness and an ArrayList wouldn't do this without programming the uniqueness into the method that would 'add' the elements.
If I have an ArrayList that is returned as a Collection and is then down cast into a HashSet I should have no problem becuase the 'architecture' of the ArrayList / HashSet is almost the same. I.E. They mimic a one dimensional array of 'Objects'.
My problem is here.. what happens if I upcast from ArrayList to Collection (the returned type), my 'calling' program receives this Collection and down casts it into a HashMap. This is still a collection, but, it is a functional diffrent collection in the sanse that is almost mimics a 2 dimensional array of key/value pairs.
Will my HashMap be populated with the objects in the collection with null or "" keys? Or will we lost something in the cast?
I know that you should not lose functionaly when you cast, but what about functionality that was never there to begin with?

SOURCE CODE should be SURROUNDED by "code" tags.
John Bateman
Ranch Hand

Joined: Mar 09, 2000
Posts: 320
Hi all
I think I may have found my answer.
If I am correct I can't go from ArrayList -> Collection -> HashMap because HashMap implements Map interface and not Collection or List. So I was mistaken, they are not on the same 'path' in the hierarchy tree.
I can however go from ArrayList -> Collection -> HashSet because HashSets are Lists which are sub classes of the Collection interface.

[This message has been edited by John Bateman (edited March 09, 2001).]
Martha Yeh

Joined: Jan 31, 2001
Posts: 18
here is the hierachy of the collection:
Collection-->Set--> SortedSet
also, the Collection interfacces and the classes that implement them:
List-->ArrayList, Vector, and LinkedList
Map-->HashMap, HashTable
hope this will help.
good day ^__^*
I agree. Here's the link:
subject: Casting through diffrent tree branches.
jQuery in Action, 3rd edition