0

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

3 Answers 3

2

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";
Sign up to request clarification or add additional context in comments.

1 Comment

The values of 1 and 2 still appear to be strings in this code. When I add the two together, i get the result of 12 ("1"+"2") and not 3 (1+2)
0

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";

1 Comment

My fault for not pointing this out earlier. I need to be able to sort the array. From what I understand, Objects are not sortable.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.