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 › What does it mean to "cast"
Page Index Toggle Pages: 1
What does it mean to "cast"? (Read 682 times)
What does it mean to "cast"?
Jul 2nd, 2009, 12:22pm
 
Hello,

I was going through the Processing reference for subset()

http://processing.org/reference/subset_.html

and I came across this line:

Quote:
"When using an array of objects, the data returned from the function must be cast to the object array's data type. For example: SomeClass[] items = (SomeClass[]) subset(originalArray, 0, 4)."


I have no idea what the part in bold means. What does it mean to "cast" to the object array's data type?
Re: What does it mean to "cast"?
Reply #1 - Jul 2nd, 2009, 12:37pm
 
Nothing to do with spells nor Harry Potter, I think...
Probably more related to molds...

To cast to a type is to force its types to something related/compatible, in order to get more functionalities or to force it to have some characteristics.

For example, you can cast a float to an int to get rid of the decimal part:
float x = 5.236;
int i = (int) x;


In the case of collections, like ArrayList, you store only generic objects, so when you get them back, you have to cast them to their original type.

I don't know why it is necessary for subset, but it in the same spirit.
Re: What does it mean to "cast"?
Reply #2 - Jul 2nd, 2009, 7:29pm
 
I came up against this when I started using ArrayLists instead of regular arrays to hold my objects. When you make a regular array, you make it of the same type as the object it holds. Arraylists don't have a specific type (as far as i understand this) and when operating on an object in that ArrayList, it becomes necessary to put it into a placeholder object, using casting.
Code:

Arraylist stuff;

stuff.add(new ball());
stuff.add(new ball());
stuff.add(new ball());

for(int i=0;i<stuff.size();i++){
ball frank = (ball) stuff.get(i);

frank.doStuff();
frank.bounce();
}
Page Index Toggle Pages: 1