Skip to content
Advertisement

Is there a “right “way to store a String and an Integer in the same array in Java?

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 int items, use the .toString() method to convert it to a String and store it in an array of Strings.

  • If the number of Integer elements will be much lower than the Strings, use the .toString() method to convert it to a String and store it in an array of Strings. Then parse the ints back out using Integer.parseInt().(parseInt() is considered a slow operation)

  • If memory is not a concern, make two separate arrays of the same size, one of type String and another of type int. Choose one to be primary(most populated). Use a flag value(“” for String and Integer.MIN_VALUE for int) 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.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement