Because you are relying on autoboxing when you wrote
Object prova = 9.2;
If you want it to be a Float, try
Object prova = 9.2f;
Remember that java.lang.Float and java.lang.Double are sibling types; the common type is java.lang.Number
If you want to express a Number in whatever format, use the APIs, for example Number.floatValue()
Answer from Dilum Ranatunga on Stack OverflowBecause you are relying on autoboxing when you wrote
Object prova = 9.2;
If you want it to be a Float, try
Object prova = 9.2f;
Remember that java.lang.Float and java.lang.Double are sibling types; the common type is java.lang.Number
If you want to express a Number in whatever format, use the APIs, for example Number.floatValue()
Because prova is a Double, and Double is not a subtype of Float.
Either you could start with a float literal: 9.2f (in which case prova would actually be a Float) or, you could it like this:
Float prova2 = ((Double) prova).floatValue();
Because you are relying on autoboxing when you wrote
Object prova = 9.2;
If you want it to be a Float, try
Object prova = 9.2f;
Remember that java.lang.Float and java.lang.Double are sibling types; the common type is java.lang.Number
If you want to express a Number in whatever format, use the APIs, for example Number.floatValue()
Because prova is a Double, and Double is not a subtype of Float.
Either you could start with a float literal: 9.2f (in which case prova would actually be a Float) or, you could it like this:
Float prova2 = ((Double) prova).floatValue();
java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.Float
java - ClassCastException Double to Float even when I'm not using a Double - Stack Overflow
java - Possible lossy conversion from double to float, given float values? - Stack Overflow
Convert double to float in Java - Stack Overflow
You can fix this by adding @specialized(Float) to the A: ClassTag type parameter.
Here's a slightly simplified version of your code with the added @specialized(Float) tag. (I also added @specialized(Int) to make the example more complete.)
import scala.reflect.ClassTag
class Test[@specialized(Float, Int) A: ClassTag] {
def apply(count: Int): Array[A] = Array.tabulate(count) {
i => (1.5 + i).asInstanceOf[A];
}
}
val floatTest = new Test[Float];
println(floatTest(5).mkString(", ")); // 1.5, 2.5, 3.5, 4.5, 5.5
// Works because code is specialized for float
// and primitive double is cast to primitive float.
val doubleTest = new Test[Double];
println(doubleTest(5).mkString(", ")); // 1.5, 2.5, 3.5, 4.5, 5.5
// Works although code is not specialized for double
// but Double object can be cast to Double object.
val intTest = new Test[Int];
println(intTest(5).mkString(", ")); // 1, 2, 3, 4, 5
// Works because code is specialized for int
// and primitive double is cast to primitive int.
val longTest = new Test[Long];
println(longTest(5).mkString(", ")); // ClassCastException
// Fails because code is not specialized for long
// and Double object cannot be cast to Long object.
// Works if you add @specialized(Long).
(The no-op cast from Double object to Double object is called identity conversion.)
You can also omit the list of types from @specialized. In this case, the class will be specialized for all primitive types:
class Test[@specialized A: ClassTag] {
...
Be aware though that this will generate a lot more class files. For example, if all Scala collection classes would be specialized for all primitive types, the Scala language library would suddenly become about ten times as large.
The root problem is this: The casting rules for boxed primitives are very different from the casting rules for unboxed primitives.
In this case (using Java syntax):
double d = 1.0 / 5.0; // 0.2 as a double primitive value
float f = (float)d; // 0.2f as a float primitive value
Works as expected. The cast from double to float is known as narrowing primitive conversion.
But this doesn't work:
java.lang.Double d = 1.0 / 5.0; // 0.2, but in a java.lang.Double object
java.lang.Float f = (java.lang.Float)d; // ClassCastException
No narrowing or widening conversion from java.lang.Double to java.lang.Float is possible because neither is a subclass of the other, and boxing and unboxing conversions are not applied either. More precisely, there is an implicit boxing conversion from double to java.lang.Double in the first line, but no implicit boxing or unboxing conversion is applied in the second line.
Scala makes the issue even more confusing because it tries to hide the distinction - Scala only has type Double, but no type double. Depending on context, the Scala type Double is sometimes (I think most of the time) mapped to the Java primitive type double and sometimes to the Java reference type java.lang.Double.
This is actually a few leaky abstractions interacting. .asInstanceOf[A] doesn't become .asInstanceOf[Float] when A happens to be Float; it's really .asInstanceOf[Object] which gives you in this case a java.lang.Double. It has to be that way because there is just one class test, not a separate version for different As, and .asInstanceOf[Object] is a completely different operation from .asInstanceOf[Float] in JVM bytecode.
The cast to Float is added later and invisible in your code, and then java.lang.Double can't be cast to it (unlike a Double!).
I think the most reasonable way is defining a typeclass (Numeric is mentioned in the comments, but it doesn't have the method we want).
trait FromDouble[A] {
def apply(x: Double): A
}
object FromDouble {
implicit object DoubleFromDouble extends FromDouble[Double] {
def apply(x: Double) = x
}
implicit object FloatFromDouble extends FromDouble[Float] {
def apply(x: Double) = x.toFloat
}
// optional, to simplify test.arr a bit
def applyA(implicit fromDouble: FromDouble[A]) = fromDouble(x)
}
class test[A : ClassTag : FromDouble] {
private val arr: Array[A] = Array.tabulate(10){ x=>
FromDoubleA / 5.0)
}
def apply(i: Int): A = arr(i)
}
If I'm not mistaken,
0.5are decimal numbers; thus, making it a float value.
You should not rely solely on your intuition when learning a new programming language.
In fact, 0.5 is a double literal. For a float literal you need to write 0.5f.
As The Java Language Specification (JLS 3.10.2) states:
A floating-point literal is of type
floatif it is suffixed with an ASCII letterForf; otherwise its type isdoubleand it can optionally be suffixed with an ASCII letterDord.
See also:
- The Oracle Java Tutorial > Primitive Data Types
You have two options.
One is change your method's return type to double.
The other is change the double values you are returning to float values, as many have said in the comments.
public float typeDmgMultiplr(String type,String type2){
if(type.equalsIgnoreCase("grass")){
if(type2.equalsIgnoreCase("grass"))
return 0.5f;
else if(type2.equalsIgnoreCase("poison"))
return 0.5f;
else if(type2.equalsIgnoreCase("fire"))
return 0.5f;
else
return 2.0f;
}
else if(type.equalsIgnoreCase("fire")){
if(type2.equalsIgnoreCase("grass"))
return 2.0f;
else if(type2.equalsIgnoreCase("poison"))
return 1.0f;
else if(type2.equalsIgnoreCase("fire"))
return 0.5f;
else
return 0.5f;
}
else if(type.equalsIgnoreCase("water")){
if(type2.equalsIgnoreCase("grass"))
return 0.5f;
else if(type2.equalsIgnoreCase("poison"))
return 1.0f;
else if(type2.equalsIgnoreCase("fire"))
return 2.0f;
else
return 0.5f;
}
else{
if(type2.equalsIgnoreCase("grass"))
return 2.0f;
else if(type2.equalsIgnoreCase("poison"))
return 0.5f;
else if(type2.equalsIgnoreCase("fire"))
return 1.0f;
else
return 1.0f;
}
}
Just cast your double to a float.
double d = getInfoValueNumeric();
float f = (float)d;
Also notice that the primitive types can NOT store an infinite set of numbers:
float range: from 1.40129846432481707e-45 to 3.40282346638528860e+38
double range: from 1.7e–308 to 1.7e+308
Convert Double to Float
public static Float convertToFloat(Double doubleValue) {
return doubleValue == null ? null : doubleValue.floatValue();
}
Convert double to Float
public static Float convertToFloat(double doubleValue) {
return (float) doubleValue;
}
Well, your second statement is correct by Java's standards, but in your first example Java is probably trying to prevent you from converting doubles to floats due to a loss of precision that must be explicitly asked for by the programmer, as so:
double a = //some double;
float b = (float) a; //b will lose some of a's precision
According the Java grammar, the f suffix is only applicable to float literals. Your second statement should work. The first however is an expression and therefore requires a cast:
springing[n] = (float)(.05*(.17*(n+1)));
It would help if you provide a stacktrace.
Otherwise, the standard solution is to replace (Float) someLongValue with someLongValue.floatValue()
If you are dealing with primitive types, you can just cast from long to float, although it is a 5.1.2 Widening Primitive Conversion, but one that may lose precision, so be careful! Obviously you have the wrapper type Long, which cannot implicitly be converted, thus you get the classcastexception. This may be because of autoboxing, or explicit Long object creation.
Some more uninvited advice: if your valid values are decimals in the range of -10 to +10 the standard data type is int (primitive). avoid float if you mean exact numbers. long is also not optimal, because it is not fully atomic like int and it takes 2x the memory. If you allow a different state "not assigned" then Integer, which may take null, is also OK.
The exception happens because the compiler recognizes that Long and Float do not have a parent-child dependency. Unlike C++, which will try to find an overloaded cast operator.
You can call doubleValue() on any of the primitive wrapper types that are derived from Number, so this is the recommended way to do what you want:
double val = ((Number)textField.getValue()).doubleValue()
A couple of things to note here: first, I casted the output of getValue() to Number. That way, you can change your mind and actually return Double values in the future, and you won't break.
Also, I'm using double values, not float. The JVM works with double internally, so there's no reason to use float except to save space in an array.
You cannot cast directly from Double to Integer. You need to do the following:
Double d = new Double(1.23);
int i = d.intValue();
as suggested in How to convert Double to int directly?
Try this
lowestCost.put(lowestVertex, (Integer) new Double(tempVal).intValue());
Hope it will resolve your issue