Why doesn't Java have true multidimensional arrays?

前端 未结 6 1111
夕颜
夕颜 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:06

    If you want a fast implementation of a true multi-dimentional array you could write a custom implementation like this. But you are right... it is not as crisp as the array notation. Although, a neat implementation could be quite friendly.

    public class MyArray{
        private int rows = 0;
        private int cols = 0;
        String[] backingArray = null;
        public MyArray(int rows, int cols){
            this.rows = rows;
            this.cols = cols;
            backingArray  = new String[rows*cols];
        }
        public String get(int row, int col){
            return backingArray[row*cols + col];
        }
        ... setters and other stuff
    }
    

    Why is it not the default implementation?

    The designers of Java probably had to decide how the default notation of the usual C array syntax would behave. They had a single array notation which could either implement arrays-of-arrays or true multi-dimentional arrays.

    I think early Java designers were really concerned with Java being safe. Lot of decisions seem to have been taken to make it difficult for the average programmer(or a good programmer on a bad day) to not mess up something . With true multi-dimensional arrays, it is easier for users to waste large chunks of memory by allocating blocks where they are not useful.

    Also, from Java's embedded systems roots, they probably found that it was more likely to find pieces of memory to allocate rather than large chunks of memory required for true multi-dimentional objects.

    Of course, the flip side is that places where multi-dimensional arrays really make sense suffer. And you are forced to use a library and messy looking code to get your work done.

    Why is it still not included in the language?

    Even today, true multi-dimensional arrays are a risk from the the point of view of possible of memory wastage/misuse.

提交回复
热议问题