I want a 2D Matrix with one line of strings and the other line with int's. Is that possible? Or do I have to save the int's as strings and later convert them to int's again?
-
5It's sort of possible, but it's usually a very bad idea. You could create an array of Object[][] and add String and Integers to it. But don't do this. If you need to connect a String and an int, create a class that does this, and then create a single dimensional collection or array of objects of this type.Hovercraft Full Of Eels– Hovercraft Full Of Eels2013-06-25 11:53:20 +00:00Commented Jun 25, 2013 at 11:53
-
1Duplicate? stackoverflow.com/questions/5809486/…germi– germi2013-06-25 11:55:21 +00:00Commented Jun 25, 2013 at 11:55
-
Make a wrapper or use a HashMapEdward J Beckett– Edward J Beckett2015-12-12 09:15:19 +00:00Commented Dec 12, 2015 at 9:15
7 Answers
Rather use an object.
class MyEntry {
String foo;
int number;
}
MyEntry[] array = new MyEntry[10];
But if you absolutely must for some unfortunate reason, you can use two types - only through an Object supertype.
Object[][] arr = new Object[2][10];
arr[0][0] = "Foo";
arr[1][0] = new Integer(50);
Comments
No it is not possible . There can be only a single datatype for an array object. You can make a class having both the int and String as property and use it. Never use an Object[][] even if there is a temptation to do so, it is an evil workaround and hacks fail more than they succeeded . If Object was a sound technique then they wouldn't have introduced Generics for Collection !
4 Comments
Integers inherit , int doesn't !Object[][] array for this is like shooting at ones own foot . Anyone suggesting to use it is wrong enough if my answer is wrong.You can create an array of the type Object and store any non-primitive Object in there. When you retrieve them, you'll need to make sure you check their class though.
if(objArray[0] instanceof String) {
// do string stuff
} else if(objArray[0] instanceof Integer) {
// do integer stuff
}
etc.
I think you're better off creating a new class that can store objects of the types that you want and just retrieve them using getters and setters. It's a lot safer and more stable.
Comments
You could do it if you do a 2D array of Object as in Object[][] myArray = new Object[x][y] where x and y are numbers.
All you would have to do is cast the Objects to their expected types before using them. Like (String) myArray[0][3] for example.
YOu should only do it this way if you know for certain what type the Object in a particular location will be.
However, it's generally not a good idea to do things this way. A better solution would be to define your own data structure class that has a String array and an int array as member variables. As in:
public class myData {
String[] theStringArray;
int[] theIntArray;
public myData(String[] sArraySize, int[] iArraySize) {
this.theStringArray = new String[sArraySize];
this.theIntArray = new int[iArraySize);
}
...
// Additional getters / setters etc...
...
}