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);
I am struggling with a problem, which I can't understand why it doesn't work. How do I pass a variable through the double obj
and convert to int
?
Why does it not work in the top code snippet, but it works in the bottom code snippet below the line?
The only difference seems to be adding an extra variable, which is also typed as a 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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
double
是原始类型,而Double
是常规 Java 类。您不能调用原始类型的方法。不过,intValue()
方法可在Double
上使用,如 javadoc可以找到有关这些基本类型的更多阅读 此处
The
double
is a primitive type, while theDouble
is a regular Java class. You cannot call a method on a primitive type. TheintValue()
method is however available on theDouble
, as shown in the javadocSome more reading on those primitive types can be found here
您在顶部的代码片段中,尝试将 Double 对象分配给像这样的基本类型。
这当然可以工作,因为拆箱(将包装类型转换为其等效的原始类型),但您面临的问题是取消引用
doublehelpermethod
。不可能,因为
doublehelpermethod
是原始类型变量,无法使用点关联。
请参阅... 自动装箱You're in the top snippet, trying to assign a Double object to a primitive type like this.
which would of course work because of unboxing (converting a wrapper type to it's equivalent primitive type) but what problem you're facing is dereferencing
doublehelpermethod
.is not possible because
doublehelpermethod
is a primitive type variable and can not be associated using a dot.
See... AutoBoxing