Is it possible to use mulitple possible types in Java?

Viewed 30

What I want is a property that is a map with a key of type String, where the value can be either a String OR another map:

Map<String, String or Map<String, String>> traits();

Is this possible in Java?

1 Answers

There are two ways to do it, either your generics or Object.

  1. Map<String, ?> stringObjectMap.get = new HashMap<>();
  2. Map<String, Object> stringObjectMap.get = new HashMap<>();
if(stringObjectMap.get("key") instanceof Map) return (Map)stringObjectMap.get("key");
        else return (String)stringObjectMap.get("key");
Related