在哪里放置括号以简洁地将转换对象转换为原始类型而不自动拆箱?

发布于 2024-09-27 00:13:05 字数 164 浏览 0 评论 0原文

通过自动拆箱,此语句将自动起作用:

int myPrimitive = (Integer) doIt();

但是,如果我想在一行中显式地从 Integer 转换为 int,我必须在哪里放置括号?

With autounboxing, this statement will automatically work:

int myPrimitive = (Integer) doIt();

But if I want to explicitly convert from an Integer to an int here in a single line, where do I have to put the parentheses?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

邮友 2024-10-04 00:13:05

您可以这样做:

int myPrimitive = (int) (Integer) doIt();

但正如您所说,自动拆箱将为您提供

一个示例来展示链式转换的工作原理(永远不要使用此代码):

Map notReallyAMap = (Map) (Object) new String();

链式转换的问题是,无论您在哪里使用它,要么转换为合法,可以去除中间商;否则转换只会导致 ClassCastException。所以你永远不应该使用它

You could do this :

int myPrimitive = (int) (Integer) doIt();

But as you said, auto-unboxing will get that for you.

A bad example to show that chain casts work (don't ever use this code) :

Map notReallyAMap = (Map) (Object) new String();

The thing with chain casts, is that wherever you use it, either the cast is legit, and you can remove intermediaries; or the cast will simply cause a ClassCastException. So you should never use it.

柳絮泡泡 2024-10-04 00:13:05

要么编译器为您拆箱 Integer,要么您自己拆箱 - 这是无法避免的。

因此,您需要执行以下操作

int myPrimitive = ((Integer) doIt()).intValue();

或更简单地更改 doIt() 以返回 int 因为您似乎更想处理 int比(可空)Integers。

Either the compiler unboxes the Integer for you, or you do it yourself - this cannot be avoided.

So you need to either do

int myPrimitive = ((Integer) doIt()).intValue();

or more simply, change doIt() to return an int since you seem to want to deal with ints rather than (null-able) Integers.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文