Home > Net >  How to individually fill Object[][]?
How to individually fill Object[][]?

Time:07-02

I‘ve never worked with this type of Array before. If you have question because I forgot something please ask :).

I have an Object[][], let’s take the size 3

Object[][] test = new Object[3][3];

Now I want to fill the Object with loop (while—loop), that’s why I have to fill it individually.

I‘ve tried stuff like this:

int i = 0;
while() {
    Icon icon = new Icon(...);
    String test = „test“;
    test[i][i] = icon, test;
    i  ;
}

This won’t work and I just couldn’t get my head around it.

As you can see I want to fill „test“ with an Icon and a String.

Help is greatly appreciated.

CodePudding user response:

You can't assign multiple values even in 2D Array, you can use code like below -

    Object[][] test = new Object[3][3];
    for (int i = 0; i < 3; i  ) {
        for (int j = 0; j < 3; j  ) {
            test[i][j] = "Some object";
        }
    }

Also just for your understanding, below is a SS for a 2D array so that you can understand how it looks -

 {{"1","2","3"},{"4","5","6"},{"7","8","9"}}

CodePudding user response:

The while loop doesn't make sense but maybe its out of context. If you want to store 3 strings and 3 icons you can do this:

     Object[][] test= new Object[3][2];
    for (int i = 0; i < test.length; i  ) {
            Icon icon = new Icon(...);
            String test = „test“;
            test[i][0] = icon;
            test[i][1] = test;
    }

However I want to point out that this is a terrible practice of storing your data, instead you could use a Tuple2, a map or create your own class.

  • Related