Technology : General Technology Notes: Diary of a late,late adopter.
Updated: 4/4/2004; 7:43:39 AM.

 

Frequent Visits

Subscribe to "Technology" in Radio UserLand.

Click to see the XML version of this web page.

Click here to send an email to the editor of this weblog.

 
 

Saturday, March 13, 2004

I had the hardest time using an ArrayList.  I had an ArrayList full of Fish objects and getting them out with ArrayList.get() and wanting to do some Fish type operations such as printing out data about the Fish and comparing it to another Fish.

To get the third Fish out of the ArrayList it is in, I tried

currentFish = myArrayList.get(2);

The trick is that ArrayLists (and other containers) store all objects as Objects instead of as Fish or Dogs or Cats or Cars or Strings.   This behavior happens for all types of java Collections.  So when you call an object back out of an ArrayList, you have to cast it back into whatever object it is supposed to be 

currentFish = (Fish)myArrayList.get(2);

Further confusion happens because every object has toString() over-ridden and automatically available so that when you think you are getting a string back from an ArrayList and want to print it out, it works fine.

I even had it print out the results of getClass() on the Object I was retrieving from myArrayList and even that told me it was a Fish!  But still, it was being treated like an Object until the cast.


7:57:53 AM    comment []

© Copyright 2004 mcgyver5.



Click here to visit the Radio UserLand website.

 


March 2004
Sun Mon Tue Wed Thu Fri Sat
  1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31      
Feb   Apr