2

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(){
    }
}
5
  • 4
    If it's only 3 distinct values, you should probably use an enum.
    – August
    Dec 26, 2014 at 6:43
  • @August Can we have constructors in enum? Dec 27, 2014 at 12:39
  • 1
    Yes, enums support constructors, methods, and fields too.
    – August
    Dec 27, 2014 at 15:58
  • @August So, when they support all three, how do u differentiate with class in usage? i understand the above example above where enum is more appropriate, but in general? Dec 27, 2014 at 16:30
  • Enums should be used when you need a set of constants: docs.oracle.com/javase/tutorial/java/javaOO/enum.html
    – August
    Dec 27, 2014 at 16:37

3 Answers 3

1

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));
4
  • One supplement query, each declared field is also an instance of the enum How do i understand this compared to class? Dec 26, 2014 at 7:07
  • @overexchange Each enum is a constant, there are only three distinct instances of your analogous class. Dec 26, 2014 at 7:16
  • So, enum Usage is not about less memory usage but about more intuitive representation of using 3 distinct elements. In C programming, we could have more control on decreasing memory usage by using bit syntax. am i correct? Dec 26, 2014 at 11:49
  • @overexchange Java Enum types are very similar to C style enum(s). Dec 26, 2014 at 15:28
1

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

1

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

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.