Why does Java allow arrays of size 0?

后端 未结 9 1078
离开以前
离开以前 2020-11-27 02:53

Arrays in java are fixed in length. Why does Java allow arrays of size 0 then?

String[] strings = new String[0];
相关标签:
9条回答
  • 2020-11-27 03:25

    Why does Java allow arrays of size 1? Isn't it pretty useless to wrap a single value in an array? Wouldn't it be sufficient if Java only allowed arrays of size 2 or greater?

    Yes, we can pass null instead of an empty array and a single object or primitive instead of a size-one-matrix.

    But there are some good arguments against such an restriction. My personal top arguments:

    Restriction is too complicated and not really necessary

    To limit arrays to sizes [1..INTEGER.MAX_INT] we'd have to add a lot of additional boudary checks,(agree to Konrads comment) conversion logic and method overloads to our code. Excluding 0 (and maybe 1) from the allowed array sizes does not save costs, it requires additional effort and has an negative impact on performance.

    Array models vector

    An array is a good data model for a vector (mathematics, not the Vector class!). And of course, a vector in mathematics may be zero dimensional. Which is conceptually different from being non-existant.


    Sidenote - a prominent wrapper for an (char-)array is the String class. The immutable String materializes the concept of an empty array: it is the empty String ("").

    0 讨论(0)
  • 2020-11-27 03:27

    Same as C++, it allows for cleaner handling when there is no data.

    0 讨论(0)
  • 2020-11-27 03:27

    Another case when a zero length array is useful is when copying a two dimensional array. I can write:

    public int[][] copyArray(int[][] array){
         int[][] newArray = new int[array.length][0];
         for(int i=0;i<array.length;i++){
             newArray[i] = array[i];
         }
         return newArray;
    

    Being that every array reference in array is being overwritten, initializing them as refernces to zero length arrays is most efficient.

    0 讨论(0)
提交回复
热议问题