Why doesn't Java have true multidimensional arrays?

前端 未结 6 1125
夕颜
夕颜 2020-12-05 06:57

The TL;DR version, for those who don\'t want the background, is the following specific question:

Question

Why doesn\'t Java have an implemen

6条回答
  •  天涯浪人
    2020-12-05 07:13

    To me it looks like you sort of answered the question yourself:

    ... an incentive to write it as a flat array, even if that makes the unnatural and hard to read.

    So write it as a flat array which is easy to read. With a trivial helper like

    double get(int row, int col) {
        return data[rowLength * row + col];
    }
    

    and similar setter and possibly a +=-equivalent, you can pretend you're working with a 2D array. It's really no big deal. You can't use the array notation and everything gets verbose and ugly. But that seems to be the Java way. It's exactly the same as with BigInteger or BigDecimal. You can't use braces for accessing a Map, that's a very similar case.

    Now the question is how important all those features are? Would more people be happy if they could write x += BigDecimal.valueOf("123456.654321") + 10;, or spouse["Paul"] = "Mary";, or use 2D arrays without the boilerplate, or what? All of this would be nice and you could go further, e.g., array slices. But there's no real problem. You have to choose between verbosity and inefficiency as in many other cases. IMHO, the effort spent on this feature can be better spent elsewhere. Your 2D arrays are a new best as....

    Java actually has no 2D primitive arrays, ...

    it's mostly a syntactic sugar, the underlying thing is array of objects.

    double[][] a = new double[1][1];
    Object[] b = a;
    

    As arrays are reified, the current implementation needs hardly any support. Your implementation would open a can of worms:

    • There are currently 8 primitive types, which means 9 array types, would a 2D array be the tenth? What about 3D?
    • There is a single special object header type for arrays. A 2D array could need another one.
    • What about java.lang.reflect.Array? Clone it for 2D arrays?
    • Many other features would have be adapted, e.g. serialization.

    And what would

    ??? x = {new int[1], new int[2]};
    

    be? An old-style 2D int[][]? What about interoperability?

    I guess, it's all doable, but there are simpler and more important things missing from Java. Some people need 2D arrays all the time, but many can hardly remember when they used any array at all.

提交回复
热议问题