0

A Hashmap contains a key with a value that can be an Integer or Double.

This works if the value is of type Double but fails for type Integer:

Double value = (Double) locationMap.get("key");

Unfortunately I cannot seem to control the type, as it is JSON data transmitted from a server. Apparently, even if the number is of type double server-side (Javascript) before transmission, but does not have decimal digits, it will be interpreted as Integer somewhere along the line on the client side (Java).

What is the shortest way to account for a possible Integer value and cast it to Double?

Manuel
  • 14,274
  • 6
  • 57
  • 130

1 Answers1

3

Assuming you know it's a Number (e.g. you tested with instanceof first):

Double value = ((Number) locationMap.get("key")).doubleValue();

This is inefficient if the number is already a Double. You may want to define a method to handle that specially:

// Doesn't handle null.
Double toDouble(Number n) {
  return (n instanceof Double) ? (Double) n : Double.valueOf(n.doubleValue());
}

The Double.valueOf looks redundant, but is necessary if using a conditional expression to avoid unboxing of the second operand (see this).

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • Works perfectly! I think you just broke the record for time to correct answer. For me at least ;) – Manuel Mar 26 '19 at 17:22