We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › linked list returning wrong Object type
Page Index Toggle Pages: 1
linked list returning wrong Object type (Read 286 times)
linked list returning wrong Object type
Jan 13th, 2009, 4:58am
 
so ...
-----------------------------
class Fish {
 
 float maxSpd, spd, slowSpd, maxTurn, nMaxTurn;
 Vector position;
 Manager manager;
 
 Fish(Manager pManager, Vector pPos) {
   manager = pManager;
   //maxSpd = pMaxSpd;
   //spd = pSpd;
   //slowSpd = pSlowSpd;
   //maxTurn = pMaxTurn;
   //nMaxTurn = pNMaxTurn;
   position = new Vector(pPos.x, pPos.y, pPos.z);
   manager.fishArray.add(this);
 }

and a little further down in another function:
Fish f1 = manager.fishArray.get(j);
------------------------------------
fishArray is an ArrayList declared in the Manager class. I get an error on that last line that says cannot convert from Object to SchoolingFish.Fish. Is there some reason that the manager.fishArray.add(this) isn't working the way I think it should be?
Re: linked list returning wrong Object type
Reply #1 - Jan 13th, 2009, 5:56am
 
Does casting help, like this?

Code:

Fish f1 = (fish)(manager.fishArray.get(j));
Re: linked list returning wrong Object type
Reply #2 - Jan 13th, 2009, 7:42am
 
Indeed it does, works perfect now. Seems really strange that I should have to do that. Thanks for the help.
Re: linked list returning wrong Object type
Reply #3 - Jan 13th, 2009, 8:37am
 
No problem.  It stems from the fact that ArrayList and other containers are designed to contain Object class, which is the root of all types of objects.

Because Fish is a subclass of Object (as all types of objects are), ArrayList will take Fish as its content.  But it can also take other objects at the same time as well (try adding some other objects, like Integer, for example).

Problem is that after you stuff things into the container, the container does not know what it contains, other than the fact that it is an Object (or its descendants).  You need to explicitly tell the compiler what it is that you expect out of the container, by casting it (hence "(Fish)" in front of the .get() statement).

There is quite an extensive discussion on this matter in this board and Java documents.  One mechanism that is available to make this process less tedious is the use of generics, which was added in Java 1.5, but this does not yet work in Processing.  

But for now, follow the convention of casting something fresh out of an ArrayList as just a convention, and things will be fine (just a bit tedious).
Page Index Toggle Pages: 1