Re: How to cast an Object to Double?
In article <ff5bm3$ei4$1@news.nems.noaa.gov>, www <www@nospam.com> wrote:
OK. My full testing program is:
public class HelloWorld
{
public static void main( String[] args )
{
Map<String, Object> map = new HashMap<String, Object>(10);
Properties states = new Properties();
try
{
states.load(new FileInputStream("property_file.txt"));
}
catch(IOException e) {
}
//copy entries from states file to the map
for (Map.Entry value : states.entrySet())
{
map.put((String)value.getKey(), value.getValue());
}
Object obj = map.get("HAT_SIZE");
double value = (Double)obj; //causing error!!!!!!!! I don't
understand why.
//following is ok, but why need to cast to String first?
double value = Double.parse((String)obj);
}
}
The property file("property_file.txt") has the content:
HAT_SIZE=5.999
SHOE_SIZE=3.23
Good. One improvement would be for your test to actually compile (i.e.
include necessary imports, and leave the duplicate working line commented out.
More importantly, if you're getting an error, TELL US what it is! When I read
your post, I thought you were getting a compile error, and I couldn't see
why - you're allowed to cast an Object to a Double.
It turns out you're NOT getting a compile error, you're getting a runtime
error, and it is
Exception in thread "main" java.lang.ClassCastException: java.lang.String
at Foo.main(Foo.java:28)
This means you're trying to cast a String into a Double. That won't work.
Casting is different than parsing. Casting is just a way to tell one part of
the code that you, the developer, have more information about the type of the
object, and you want to try to use the object as if it were this more specific
type. If it's NOT actually usable as that type, it'll get a
ClassCastException.
A String isn't a Double. It's a String. So the cast fails.
What you want is to parse the string, meaning to read it's characters and see
what double it represents. You can do that by using the
Double.parseDouble(String) method. It takes a string, so if you know the
object is a String, you can cast it. That's your
double value = Double.parseDouble((String)obj);
line (note that it's parseDouble(), not parse()).
If you don't know that, you can call toString() on it.
double value = Double.parseDouble(obj.toString());
If you want a Double object rather than a double primitive value, you can use
Double value = new Double((String)obj);
Of course, many Strings, and even more non-String objects, have string values
that can't be parsed, and you'll get a NumberFormatException.
--
Mark Rafn dagon@dagon.net <http://www.dagon.net/>