简体   繁体   中英

Can I somehow implement bracketed casting between Double and Integer classes in Java?

I know Java doesn't allow direct casting between Integer and Double classes like so:

var intList = new ArrayList<Integer>();
// code that fills intList with Integer entries

var doubleVal = (Double) intList.get(0); // Class Cast exception

I also know the reason why and the solution(s) to this.

My question is - is there a way to make this work? Can I implement something such that when I use (Double) intList.get(0) in my code, it actually gives me what I want instead of throwing an exception?

In C# I would simply override the cast operator to do this and it would work, but sadly Java doesn't allow that.

Can I somehow implement bracketed casting between Double and Integer classes in Java?

Basically no. There are no Java tricks that you can use to make a simple (Double) cast do what you want to happen here.


Your example expression (Double) intList.get(0) requires too many conversions for the compiler to be "happy". It needs to unbox the Integer to an int , widen it to a double , and then box it as a Double . Three conversions.

You have to give it some help. Here are some of the ways you could help:

  (Double) ((int) intList.get(0))

The cast to int causes the Integer to be unboxed. From there it can be widened to a double and then auto-boxed to a Double .

  (Double) (intList.get(0).doubleValue())

This does the Integer to double via the doubleValue call, and then the (Double) does the final step.

  Double.valueOf(intList.get(0).doubleValue())

As above but using an explicit call to do the boxing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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