Object.intValue()的奇怪行为
我正在努力解决一个问题,我无法理解为什么它不起作用。 如何通过double obj
传递变量并转换为int
?
为什么它不能在顶部代码片段中工作,但它在行下方的底部代码片段中有效?
唯一的区别似乎是添加了一个额外的变量,它也被输入为double
?
//Converting double to int using helper //This doesn't work- gets error message //Cannot invoke intValue() on the primitive type double double doublehelpermethod = 123.65; double doubleObj = new Double( doublehelpermethod); System.out.println("The double value is: "+ doublehelpermethod.intValue()); //-------------------------------------------------------------------------- //but this works! Why? Double d = new Double(123.65); System.out.println("The double object is: "+ doubleObj);
double
是原始类型,而Double
是常规Java类。 您无法在基本类型上调用方法。 但是,在Double
上可以使用intValue()
方法,如javadoc所示
可以在这里找到关于这些原始类型的更多阅读
你是顶级片段,试图将Double对象分配给这样的基本类型。
double doubleObj=new Double( doublehelpermethod);
这当然会因为取消装箱(将包装类型转换为它的等效原始类型)而起作用,但您面临的问题是解除引用doublehelpermethod
。
doublehelpermethod.intValue()
因为doublehelpermethod
是一个原始类型变量而不能使用点关联,所以是不可能的.
请参阅… AutoBoxing