Question

How can I create value of type String and also Collection?

I want someTimes put in this Strings and the othertimes put collections.

for example in javascript I would do

 var k;
 if (someBoolean){
    k=1;
 } else{
    k=[1,2,3];
 }

can I get this behavior of the variable in java, hack or something?

I found Solution: I created an interface and declear this Objects as this interface.

Was it helpful?

Solution

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.

OTHER TIPS

You cant. String is a final class, meaning you cannot extend upon it. A String will only ever be a String. You can have a collections that contain Strings, but a String object will only have 2 types: Object and String.

You can have a class that contains a String (or a StringBuilder) and a collection, then use that class to store/receive from

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top