-6

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.

6
  • 1
    Please be more specific. You can have a collection of Strings, or you could serialize some collection of Strings in a JSON (or XML) array. Commented May 4, 2014 at 2:20
  • no array no collections of strings I have also collection and Strings I want variable that will be in some cases string and the other to put in it Collection Commented May 4, 2014 at 2:22
  • Why not just use a Collection of Strings to begin with and fetch the Strings from the Collection later? Commented May 4, 2014 at 2:23
  • because I dont want that I will need to go into the Collection and use the get method .. Commented May 4, 2014 at 2:24
  • 2
    @user3160197 Please edit your question; at the moment it seems like a XY problem. Commented May 4, 2014 at 2:27

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.