1

I have a map of the type ConcurrentMap<String, Object> for which I want to use getOrDefault. Now the returned value is type casted into BigDecimal if key exists. When I am using the below code, I get class cast exception.

final BigDecimal value= (BigDecimal) map.getOrDefault("key", 0);

I tried using (Object)0 but it makes no sense given everything in Java is an object. If getOrDefault returns Object, then why is it throwing exception on casting 0 as Bigdecimal? I used the below and it worked

final BigDecimal value= (BigDecimal) map.getOrDefault("key", BigDecimal.ZERO);

What's the reason that 0 cannot be casted?

samabcde
  • 6,988
  • 2
  • 25
  • 41
Sonali Gupta
  • 494
  • 1
  • 5
  • 20
  • 8
    `0` is not a BigDecimal and cannot be cast to it. It can be cast to `Integer`. – Eran Jul 01 '20 at 11:01
  • Does this answer your question? [java.lang.Integer cannot be cast to java.math.BigInteger](https://stackoverflow.com/questions/53645488/java-lang-integer-cannot-be-cast-to-java-math-biginteger) [explanation of ClassCastException](https://stackoverflow.com/questions/907360/explanation-of-classcastexception-in-java) – Nowhere Man Jul 01 '20 at 14:00
  • @Eran Technically that would be boxing, not casting. – Dorian Gray Jul 06 '20 at 07:18

1 Answers1

1

You cannot cast 0 (or any Integer) to BigDecimal. If you want to convert them, use BigInteger.valueOf(0)

You can use BigDecimal.ZERO instead in your code for that specific constant.

Dorian Gray
  • 2,913
  • 1
  • 9
  • 25
  • It's, however, weird, why we can't cast an `int` to BigDecimal. – Giorgi Tsiklauri Jul 05 '20 at 15:43
  • Not weird, that's because `Ìnteger` and `BigDecimal` do not extend each other. You can only case `A` to `B` if `B extends A`. You have to use the `BigInteger.valueOf` method to convert (not cast) them.. – Dorian Gray Jul 05 '20 at 15:50