奇怪的 Java 转换异常。为什么我不能将 Long 转换为 Float?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1655120/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 18:42:55  来源:igfitidea点击:

Strange Java cast exception. Why can't I cast Long to a Float?

javacasting

提问by CJJ

Why can't I cast Long to a Float?

为什么我不能将 Long 转换为 Float?

I get this error message:

我收到此错误消息:

java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Float

java.lang.ClassCastException: java.lang.Long 不能转换为 java.lang.Float

Why is this a problem? The numbers that I'm trying to cast are decimals in the domain [-10.0, 10.0]. They start out as Object instances returned using JFormattedTextField.getValue(). But they must be converted to floats.

为什么这是个问题?我试图转换的数字是域 [-10.0, 10.0] 中的小数。它们以使用JFormattedTextField.getValue(). 但它们必须转换为浮点数。

Stack trace:

堆栈跟踪:

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Float
    at submodeler.animation.Timeline.setKeyedAttribute(Timeline.java:59)
    at submodeler.ui.attributes.TransformationAttributePanel.actionPerformed(TransformationAttributePanel.java:247)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2028)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2351)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
    at java.awt.Component.processMouseEvent(Component.java:6348)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
    at java.awt.Component.processEvent(Component.java:6113)
    at java.awt.Container.processEvent(Container.java:2085)
    at java.awt.Component.dispatchEventImpl(Component.java:4714)
    at java.awt.Container.dispatchEventImpl(Container.java:2143)
    at java.awt.Component.dispatchEvent(Component.java:4544)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4618)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4282)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4212)
    at java.awt.Container.dispatchEventImpl(Container.java:2129)
    at java.awt.Window.dispatchEventImpl(Window.java:2475)
    at java.awt.Component.dispatchEvent(Component.java:4544)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:635)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:296)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:211)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:196)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:188)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

回答by flybywire

try this:

尝试这个:

Long l = ...
Float f = new Float ((float)l.longValue());

i.e., you have to transform your Long to a primitive (i.e. non-object) type.

即,您必须将 Long 转换为原始(即非对象)类型。

回答by Andreas Petersson

It would help if you provide a stacktrace.

如果您提供堆栈跟踪会有所帮助。

Otherwise, the standard solution is to replace (Float) someLongValuewith someLongValue.floatValue()

否则,标准解决方案是替换(Float) someLongValuesomeLongValue.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.

如果你处理原始类型,你可以直接从 long 转换为 float,虽然它是5.1.2 Widening Primitive Conversion,但可能会失去精度,所以要小心!显然你有包装类型Long,它不能隐式转换,因此你得到 classcastexception。这可能是因为自动装箱或显式 Long 对象创建。

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. longis 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.

一些不请自来的建议:如果您的有效值是 -10 到 +10 范围内的小数,则标准数据类型是int(原始)。如果您的意思是确切的数字,请避免浮动。long也不是最优的,因为它不像 int 那样完全是原子的,而且它需要 2 倍的内存。如果您允许不同的状态“未分配” Integer,则可能为空的 也可以。

回答by Jason S

If you are looking to convert machine bit-representations of float/double to/from bytes, see Double.doubleToLongBitsand Float.floatToIntBitsand associated functions.

如果您希望将 float/double 的机器位表示转换为/从字节,请参阅Double.doubleToLongBitsFloat.floatToIntBits以及相关函数。

回答by kdgregory

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.

发生异常是因为编译器识别出 Long 和 Float 没有父子依赖关系。与 C++ 不同,C++ 会尝试查找重载的强制转换运算符。

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:

您可以对从 Number 派生的任何原始包装器类型调用 doubleValue(),因此这是执行所需操作的推荐方法:

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.

这里有几点需要注意:首先,我将 getValue() 的输出转换为 Number。这样,您可以改变主意并在将来实际返回 Double 值,并且不会中断。

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.

另外,我使用的是双值,而不是浮点数。JVM 在内部使用 double,因此除了为了节省数组空间之外,没有理由使用 float。

回答by evilReiko

Basically, converting long to float is as easy as this:

基本上,将 long 转换为 float 就像这样简单:

float f = (float)myLongVar;

I have no experience in using JFormattedTextField, but you can try type-casting the returned object to String, use .substring()to get the exact value, and type-cast it to long. This may not be the right approach, but it may solve your problem.

我没有使用 的经验JFormattedTextField,但您可以尝试将返回的对象类型转换为 String,用于.substring()获取确切值,然后将其类型转换为 long。这可能不是正确的方法,但它可能会解决您的问题。

回答by Android334

I had this problem when I was converting a JSONObject to a Java Object. I had to change my code from double a = (double) json.get("myJSONKey");to the following:

我在将 JSONObject 转换为 Java 对象时遇到了这个问题。我不得不将我的代码更改double a = (double) json.get("myJSONKey");为以下内容:

try {
  double a = Double.parseDouble((String) myJSONObject.get("myJSONKey"));
} catch(NumberFormatException e)
{
  System.err.out("I could not convert it to a double!! :(");
}

Note you don't have to do the try/catch but I like to just so I'm clean :).

请注意,您不必执行 try/catch,但我喜欢这样做,所以我很干净:)。

In the event you already have a long value (or int or whatever) then use String.valueOf(myInt)to get your string.

如果您已经有一个 long 值(或 int 或其他),则使用它String.valueOf(myInt)来获取您的字符串。

Hope this helps,

希望这可以帮助,

-Andrew

-安德鲁