开发者

Where do you put the parentheses to concisely convert a casted object to a primitive type without auto-unboxing?

开发者 https://www.devze.com 2023-01-19 08:44 出处:网络
With autounbox开发者_高级运维ing, this statement will automatically work: int myPrimitive = (Integer) doIt();

With autounbox开发者_高级运维ing, 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?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消