简体   繁体   中英

Can you get an 2 dimensional array from 3 dimensional array without loops in Java?

Can you get a subarray from 3 dimensional array in Java? I'm kind of new to Java and need some help.

threeDimensions[][][] = {
    {
        {false, true, false, false},
        {false, true, false, false},
        {false, true, false, false},
        {false, true, false, false},
    },
    {
        {false, false, false, false},
        {false, true, true, false},
        {false, true, false, false},
        {false, true, false, false},
    }
};

twoDimensions = threeDimensions[0];

This way doesn't work but is there a way to do it without looping?

Your way does work, but you've just got the syntax a bit wrong. It should be

boolean[][][] threeDimensions = {
    {
        {false, true, false, false},
        {false, true, false, false},
        {false, true, false, false},
        {false, true, false, false},
    },
    {
        {false, false, false, false},
        {false, true, true, false},
        {false, true, false, false},
        {false, true, false, false},
    }
};

boolean[][] twoDimensions = threeDimensions[0];

If your problem is printing it out, you need to write

System.out.println(Arrays.deepToString(twoDimensions));

It works as exactly as you think it works. You just forgot to declare twoDimensions as a two-dimension array. Do this:

Boolean twoDimensions[][] = threeDimensions[0];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM