I think that store a String and an Integer in the same array in Java would be more efficient in some cases, but I know that Java is strongly typed.
Is there a way to do that?, If there’s no, what can I do?
Advertisement
Answer
Defining “more efficient” usually means less storage space or less processor intensive. These are diametrically opposite goals. The challenge is balancing them.
You could use an Object[] type as stated before, but this would require determining the type and then casting every element to either a String or Int prior to use.
Boxing, convert to Object type, and unboxing, convert to original type, are
relatively expensive operations in Java.
Possible solutions if they must be stored using the same array index:
If you do not need to do further mathematical processing on the
intitems, use the.toString()method to convert it to aStringand store it in an array ofStrings.If the number of Integer elements will be much lower than the
Strings, use the.toString()method to convert it to aStringand store it in an array ofStrings. Then parse theints back out usingInteger.parseInt().(parseInt()is considered a slow operation)If memory is not a concern, make two separate arrays of the same size, one of type
Stringand another of typeint. Choose one to be primary(most populated). Use a flag value(“” forStringandInteger.MIN_VALUEforint) to indicate the result is the other type and should use the value stored in the other array. This preserves the common index at the expense of more memory used.
I would suggest rewriting the code to use two separate arrays if possible.