overexchange
overexchange

Reputation: 1

How do i initialize this 2D array in java?

I am looking for declaring the type of 2D array that can hold only 3 distinct values in the below code.

What could be the type of the 2D array that can take least memory for each cell and hold one of the 3 distinct values? I would then initialise such array using for-loop.

class Grid{
    X[][] twoDimArray = new X[3][3];

    Grid(){

    }

    void printElements(){
    }
}

Upvotes: 2

Views: 116

Answers (3)

Joop Eggen
Joop Eggen

Reputation: 109613

If, just if, you would need to reduce resource usage, one could store the entire grid in an int, two bits per diagram position, 9 positions: 18 bits.

int diagram;

int getValue(int x, int y) {
    int i = 2*(x + 3*y);
    return (diagram >>> i) & 0x3;
}

void setValue(int x, int y, int value) {
    int i = 2*(x + 3*y);
    int mask = 0x3 << i;
    diagram &= ~mask;
    diagram |= value << i;
}

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201537

For three values, an enum is very compelling;

enum ExampleEnum {
    ONE, TWO, THREE;

    @Override
    public String toString() {
        switch (this) {
        case ONE:
            return "One";
        case TWO:
            return "Two";
        default:
            return "Three";
        }
    }
}

Then your array declaration might look like,

ExampleEnum[][] twoDimArray = new ExampleEnum[3][3];

And you could use Arrays.deepToString(Object[]) for output like

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

Upvotes: 1

Eran
Eran

Reputation: 394146

If you need three distinct values, byte[][] is probably the most efficient you can get memory wise.

Upvotes: 1

Related Questions