views:

301

answers:

4

I've got 2 2D arrays, one int and one String, and I want them to appear one next to the other since they have the same number of rows. Is there a way to do this? I've thought about concatenating but that requires that they be the same type of array, so in that case, is there a way I could make my int array a String array?

A: 

Just cast the ints to Strings as you concatenate. The end result would be a 2D array of type String.

To concatenate an int to a String, you can just use

int myInt = 5;
String newString = myInt + "";

It's dirty, but it's commonly practiced, thus recognizable, and it works.

Stefan Kendall
String newString = String.valueOf(myInt);http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#valueOf(int)
That works too, but it's more characters :P.
Stefan Kendall
A: 

There are two ways to do this that I can see:

  1. You can create a custom data object that holds the strings and ints. This would be the best way if the two items belong together. It also makes comparing rows easier.
  2. You can create a 4D array of objects and put all the values together like this. I wouldn't recommend it, but it does solve the problem,
monksy
A: 

I hear the curse of dimensionality lurking in the background, that said - first answer that comes to mind is:

final List<int,String> list = new List<int,String>();

then reviewing op's statement, we see two [][] which raises the question of ordering. Looking at two good replies already we can do Integer.toString( int ); to get concatenation which fulfills op's problem definition, then it's whether ordering is significant or flat list and ( again ) what to do with the second array? Is it a tuple? If so, how to "hold" the data in the row ... we could then do List<Pair<Integer,String>> or List<Pair<String,String>>, which seems the canonical solution to me.

Nicholas Jordan
+1  A: 

If you want an array that can hold both Strings and ints, you basically have two choices:

  1. Treat them both as Objects, so effectively Object[][] concatArray. Autoboxing will convert your ints to Integers.

  2. Treat them both as Strings (using String.valueOf(int) and Integer.parseInt(String)).

I don't know for a fact, but would guess autoboxing is a less expensive operation that converting ints to string and back.

Further, you can always find out the value type of a cell in the array by using instanceof operator; if values are converted to String, you actually need to parse a value to find out if its just a bit of text or a text representation of a number.

These two considerations -- one a guess, the other possibly irrelevant in your case -- would support using option 1 above.