mindoverflow
mindoverflow

Reputation: 424

Decide on var type based on input string

Say we have an array named L and an input string in.
If in has a form like this [0,1,2,3], L should be an int[] containing the numbers 0, 1, 2 and 3, but if in is like this <0,1,2>, then L should be a String[] containing the Strings "0", "1" and "2".
Is this possible to do in Java? Or is there a way to define an array that accepts whatever type you put into it and then behaves like an array of that type?

I've thought about why I need this and came to the conclusion that I can kind of work around it. It requires some manual writing in the actual code, which means that it'll never be a compilable program, but unless a solution is found, I'll just use this dirty solution. Thank you for your answers!

EDIT: It seems like this problem is impossible to solve the way I want it with natural Java. I'll use the dirty solution as described above. Once again, thank you anyways. Also that strange edit was me, I didn't realize I wasn't logged in.

Upvotes: 2

Views: 93

Answers (3)

camo5hark
camo5hark

Reputation: 214

You can use an Object array because Integer and String are Object:

           java.lang.Object
                  |
       +----------+----------+  
       |                     |
       v                     |
java.lang.Number             |
       |                     |
       v                     v
java.lang.Integer    java.lang.String

Exemple:

Object[] array = new Object[] {
    0,          //integer value
    "hello",    //String value
}

or

Object[] array = new Object[2];
array[0] = 0;          //integer value
array[1] = "hello";    //String value

Upvotes: 1

Ravi
Ravi

Reputation: 31397

If there are always two type of String, then

String s = "<1,2,4>";
Object[] oArr;
if (s.contains("["))
{  
    //extract the string between the bracket
    s = s.substring(s.indexOf("[") + 1);
    s = s.substring(0, s.indexOf("]"));
    // split by comma, which return String array and convert to Integer[]
    oArr = Arrays.stream(s.split(",")).mapToInt(Integer::parseInt).boxed().toArray(Integer[]::new);

}
else
{ 
    //extract the string between the bracket
    s = s.substring(s.indexOf("<") + 1);
    s = s.substring(0, s.indexOf(">"));
    // split by comma, which return String array  
    oArr = s.split(",");
}

Upvotes: 0

DavidX
DavidX

Reputation: 1319

As Joe C suggested, you can store it as an Object[].

And when you need to utilize it, you can cast the whole Object[] into a int[] or String[] using code like this:

Integer[] integerArray = Arrays.copyOf(a, a.length, Integer[].class);
int[] intArray = Arrays.stream(integerArray).mapToInt(Integer::intValue).toArray();

or

String[] stringArray = Arrays.copyOf(a, a.length, String[].class);

Upvotes: 1

Related Questions