+ 1
2D array with different data types? (Java)
Is it possible to make a multidimensional array that has different data types. I wanted to have a 2 dimensional array that had a character and an integer (Ex: B1, A5, H12 kinda like a grid), then store a random number in it. Is it even possible to make this with an array? If not, what would be the best way to do it?
5 Respuestas
+ 7
D_Stark
I know that every object is a child of the class java.lang.Object.
And I think inside the array the values are from type Object, but printing the classnames gives you Integer, String and so on.
I made a little example:
https://code.sololearn.com/czDcOHyts7zv/?ref=app
+ 20
D_Stark
I think it is possible
Object[][] obj = {{1,2,3,4,5,6},
{"hello","world"},
{2.5,3.5,6.5},
{1,"Programme",10.0}};
+ 10
Its not possible to have 2 diffrent types in an array its either String,int or char ect.. "but" it is possible to make your String array work that way, after you have created your array you can use methods to treat the element as part String and part Integer.
+ 7
Sumit Programmer😎😎 nice buddy i never knew this! 2years later and java still surprises me 😂
do you have any info on this object array im assuming that the ints are autoboxed to Integer?
+ 4
I think you should make a class with two attributes, the fist will be a char and the second an integer, and after that you can easily make arrays with the instances of that class. You'll just need to define set and get methods.
public class Pair{
private char c;
private int I;
...
}