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?
If you want an array that can hold both String
s and int
s, you basically have two choices:
Treat them both as Objects, so effectively
Object[][] concatArray
. Autoboxing will convert your ints to Integers.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.
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.
There are two ways to do this that I can see:
- 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.
- 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,
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.
精彩评论