简体   繁体   English

ClassCastException,将Integer转换为Double

[英]ClassCastException, casting Integer to Double

ArrayList marks = new ArrayList();
Double sum = 0.0;
sum = ((Double)marks.get(i));

Everytime I try to run my program, I get a ClassCastException that states: java.lang.Integer cannot be cast to java.lang.Double 每次我尝试运行我的程序时,都会遇到一个ClassCastException:java.lang.Integer无法强制转换为java.lang.Double

We can cast an int to a double but we can't do the same with the wrapper classes Integer and Double : 我们可以将int转换为double但我们不能对包装类IntegerDouble执行相同的操作:

 int     a = 1;
 Integer b = 1;   // inboxing, requires Java 1.5+

 double  c = (double) a;   // OK
 Double  d = (Double) b;   // No way.

This shows the compile time error that corresponds to your runtime exception. 这显示了与运行时异常相对应的编译时错误。

Well the code you've shown doesn't actually include adding any Integers to the ArrayList - but if you do know that you've got integers, you can use: 嗯,你已经证明实际上不包括添加任何整数到代码ArrayList -但如果知道你有整型,你可以使用:

sum = (double) ((Integer) marks.get(i)).intValue();

That will convert it to an int , which can then be converted to double . 这会将它转换为int ,然后可以将其转换为double You can't just cast directly between the boxed classes. 你不能直接在盒装类之间投射。

Note that if you can possibly use generics for your ArrayList , your code will be clearer. 请注意,如果您可以为ArrayList使用泛型,那么您的代码将更加清晰。

The code posted in the question is obviously not aa complete example (it's not adding anything to the arraylist, it's not defining i anywhere). 问题中发布的代码显然不是一个完整的例子(它没有向arraylist添加任何东西,它不是在任何地方定义i )。

First as others have said you need to understand the difference between primitive types and the class types that box them. 首先,正如其他人所说,您需要了解原始类型与封装它们的类类型之间的区别。 Eg Integer boxes int , Double boxes double , Long boxes long and so-on. 例如IntegerintDoubledoubleLonglong等上。 Java automatically boxes and unboxes in various scenarios (it used to be you had to box and unbox manually with library calls but that was deemed an ugly PITA). Java会在各种场景中自动进行装箱和取消装箱(过去你必须手动装箱和取消装箱库调用,但这被认为是一个丑陋的PITA)。

http://docs.oracle.com/javase/tutorial/java/data/autoboxing.html http://docs.oracle.com/javase/tutorial/java/data/autoboxing.html

You can mostly cast from one primitive type to another (the exception being boolean ) but you can't do the same for boxed types. 您可以主要从一种基本类型转换为另一种基本类型(例外是boolean )但您不能对盒装类型执行相同操作。 To convert one boxed type to another is a bit more complex. 将一个盒装类型转换为另一个类型有点复杂。 Especially if you don't know the box type in advance. 特别是如果你事先不知道盒子类型。 Usually it will involve converting via one or more primitive types. 通常它将涉及通过一种或多种原始类型进行转换。

So the answer to your question depends on what is in your arraylist, if it's just objects of type Integer you can do. 所以你的问题的答案取决于你的arraylist中的内容,如果它只是Integer类型的对象你可以做。

sum = ((double)(int)marks.get(i));

The cast to int will behind the scenes first cast the result of marks.get to Integer , then it will unbox that integer. cast to int将在幕后首先将marks.get的结果marks.getInteger ,然后将unbox整数。 We then use another cast to convert the primitive int to a primitive double . 然后我们使用另一个强制转换将原始int转换为原始double Finally the result will be autoboxed back into a Double when it is assigned to the sum variable. 最后,当将结果分配给sum变量时,结果将自动退回到Double (asside, it would probablly make more sense for sum to be of type double rather than Double in most cases). (请注意,在大多数情况下,总和可能更有意义的是double类型而不是Double类型)。

If your arraylist contains a mixture of types but they all implement the Number interface (Integer, Short, Long, Float and Double all do but Character and Boolean do not) then you can do. 如果您的arraylist包含多种类型的混合,但它们都实现了Number接口(Integer,Short,Long,Float和Double都可以,但不包括Character和Boolean),那么你可以这样做。

sum = ((Number)marks.get(i)).doubleValue();

If there are other types in the mix too then you might need to consider using the instanceof operator to identify them and take appropriate action. 如果混合中还有其他类型,那么您可能需要考虑使用instanceof运算符来识别它们并采取适当的操作。

2 things to understand here - 这里要理解的两件事 -

1) If you are casting Primitive interger to Primitive double . 1)如果要将Primitive interger为Primitive double It works. 有用。 eg It works fine. 它工作正常。

int pri=12; System.out.println((double)pri);

2) if you try to Cast Integer object to Double object or vice - versa , It fails. 2)如果你试图将Integer对象转换为Double对象,反之亦然,它会失败。

Integer a = 1; Double b = (double) a; // WRONG. Fails with class cast excptn

Solution - 方案 -

Soln 1) Integer i = 1; Double b = new Double(i);
soln 2) Double d = 2.0; Integer x = d.intValue();

specify your marks: 指定你的标记:

List<Double> marks = new ArrayList<Double>();

This is called generics. 这称为泛型。

Changing an integer to a double 将整数更改为double

int abc=12; //setting up integer "abc"

System.out.println((double)abc); 

The code will output integer "abc" as a double, which means that it will display as "12.0". 代码将输出整数“abc”作为double,这意味着它将显示为“12.0”。 Notice how there is a decimal place, indicating that this precision digit has been stored. 注意如何存在小数位,表示已存储该精度数字。

Same with double if you want to change it back, 如果要更改它,则与double相同,

double number=13.94;

System.out.println((int)number); 

This code will print on one line, "number" as an integer. 此代码将在一行上打印,“number”作为整数打印。 The output will be "13". 输出将为“13”。 Notice that the value has not been rounded up, the data has actually been omitted. 请注意,该值尚未向上舍入,实际上已省略了数据。

sum = Double.parseDouble(""+marks.get(i));
Integer x=10;
Double y = x.doubleValue();

This means that your ArrayList has integers in some elements. 这意味着您的ArrayList在某些元素中具有整数。 The casting should work unless there's an integer in one of your elements. 除非你的一个元素中有一个整数,否则转换应该有效。

One way to make sure that your arraylist has no integers is by declaring it as a Doubles array. 确保你的arraylist没有整数的一种方法是将它声明为双打数组。

    ArrayList<Double> marks = new ArrayList<Double>();

I think the main problem is that you are casting using wrapper class, seems that they are incompatible types. 我认为主要的问题是你使用包装类进行转换,似乎它们是不兼容的类型。

But another issue is that "i" is an int so you are casting the final result and you should cast i as well. 但另一个问题是“i”是一个int,所以你要投出最终结果,你也应该投我。 Also try using the keyword "double" to cast and not "Double" wrapper class. 另外尝试使用关键字“double”来强制转换而不是“Double”包装类。

You can check here: 你可以在这里查看:

Hope this helps. 希望这可以帮助。 I found the thread useful but I think this helps further clarify it. 我发现该线程很有用,但我认为这有助于进一步澄清它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM