cerealspiller
cerealspiller

Reputation: 1401

Android: Storing int and String values in one multidimensional array

is it possible to store different values into a multidimensional array such as int's and String's?

String[][] mainArray= new String[2][2];

    mainArray[0][0] = 1;
    mainArray[0][1] = "Name1";
    mainArray[1][0] = 2;
    mainArray[1][1] = "Name2";

this obviously doesn't work because 1 and 2 are not String values

Upvotes: 0

Views: 3259

Answers (3)

Android Killer
Android Killer

Reputation: 18509

Here is the solution

Object[][] arr=new Object[anysize][]; and you can do like this
arr[0][0]=1;
arr[1][0]="hello";

But while accessing this array you should also do this using Object only.Else there may be ClassCastException.

Upvotes: 0

Parag Chauhan
Parag Chauhan

Reputation: 35986

yes you can store try this

        String[][] mainArray= new String[2][2];

        mainArray[0][0] = String.valueOf(1);
        mainArray[0][1] = "Name1";
        mainArray[1][0] = String.valueOf(2);
        mainArray[1][1] = "Name2";

Upvotes: 2

MByD
MByD

Reputation: 137442

You can create an Object array, and save Integers, which is the boxing of the primitive int.

Object[][] arr = new Object[2][2];
arr[0][0] = "hello";
arr[0][1] = Integer.valueOf(1);
arr[1][0] = Integer.valueOf(2);
arr[1][1] = "world";

Upvotes: 0

Related Questions