Search code examples
javaeclipsetype-conversioneclipse-mars

Why eclipse reports casting error from float to double


Does anyone know why eclipse is reporting a double to float casting error in this scenario?

What is odd is even if I disable the feature to remove unnecessary casting it is still removed and reported as an error. Isn't this just silly?

enter image description here

I'm running this version of eclipse: Version: Mars.2 Release (4.5.2) Build id: 20160218-0600

enter image description here


Solution

  • You are mixing boxing with generics and that a thing that differs between the Eclipse compiler and Javac. In your particular case, this was probably fixed in Neon. At least, it works in Oxygen.1.

    Consider the following code, which work in Eclipse and Javac:

    Float f = Float.valueOf("1.0");
    System.out.println("f: " + f);
    double val = f;
    System.out.println("val: " + val);
    

    But in your case, your are using a Collection<T>:

    Collection<Float> f = Collections.singleton(Float.valueOf("1.0"));
    System.out.println("f: " + f);
    double val = Collections.min(f); // ECJ thinks Object!
    System.out.println("val: " + val);
    

    The use of generics here is the key part, and from experience, it is where Eclipse and Javac differs most. I can't tell you the specific but in that case, Eclipse simply ignore the fact that the T of the collection is a primitive wrapper and don't do unboxing, but instead fails with a cast error.

    TL;DR: use Eclipse Oxygen.1 :)

    If you really can't, use doubleValue() as in:

    double val = Collections.min(f).doubleValue();
    

    And ensure that the collection is not empty and does not contains nulls.