[Solved] JAVA variable as 2 types [closed]


Java does not support union types; however, both of these types share the same base Object class, so you could assign either one of them to a variable defined like this

 Object something;
 something = "Hello World!";
 something = new ArrayList(); // this is a collection.

Odds are that you probably were thinking of a Collection of Strings, in which case, you define it like Collection<String>

 Collection<String> strings = new ArrayList<String>();
 strings.add("Hello");
 strings.add("World");
 strings.add("!");

If that’s not what you wanted, and you really want to sometimes store a String and sometimes store a Collection, remember that Java enforces strict type checking. This means that variables cannot just store anything, they must store something that is type compatible.

String and Collection are too different to be considered type compatible without some seriously bad programming (like using Object) or something even stranger.

solved JAVA variable as 2 types [closed]