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 › Cannot cast from Object to float
Page Index Toggle Pages: 1
Cannot cast from Object to float (Read 4009 times)
Cannot cast from Object to float
Nov 29th, 2008, 7:02am
 
I want to have a ArrayList filled with floats. But I get an error:  Cannot cast from Object to float

The error is because of the line in draw()function  where I get the data from the arraylist:

for (int i = 0; i < numbers.size(); i++) {
 float current_number = (float)numbers.get(i);
}

How can I fix this ?
Re: Cannot cast from Object to float
Reply #1 - Nov 29th, 2008, 7:08am
 
Try:

for (int i = 0; i < numbers.size(); i++) {
 float current_number = (Float)numbers.get(i);
}

float is a primitive data type.  You can't store primitives (float) in an ArrayList (ref 1), so you need to use a Float container instead of float.  Basically, Float is an object that represents float primitive (ref 2).

There is something called autoboxing in Java that allows you to freely convert Float to float without explicitly stating it, so you can do something like

Float f1 = 10f
float f2 = f1;


without a hitch. The reason you can't use (float) is that autoboxing is a process that's discrete from casting (more specifically, it's akin to a conversion from a "pointer" variable to an actual float value), and the compiler interprets them as such (ref 3).  Consequently, you need to .get() an object from the ArrayList, cast it into Object subclass (Float), and let the Float object autobox it into its primitive equivalent, which is float.


Of course, I'm assuming you've already used Float to store the values, so here is the complete demo:

import java.util.ArrayList;

ArrayList al = new ArrayList();

al.add(new Float(10f));
al.add(new Float(20f));

for(int i = 0; i < al.size(); i++){
 float f = (Float)al.get(i);
}

###########################################
ref 1:

http://java.sun.com/j2se/1.4.2/docs/api/java/util/ArrayList.html

ref 2:

http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Float.html

ref 3:

http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html
Page Index Toggle Pages: 1