Why does Java allow arrays of size 0?

后端 未结 9 1109
离开以前
离开以前 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:15

    Another case where a zero length array can be useful: To return an array containing all of the elements in a list :

     T[ ] toArray(T[ ] a)
    

    A zero length array can be used to pass the type of the array into this method. For example:

    ClassA[ ] result = list.toArray(new ClassA[0]);
    

    A zero length array is still an instance of Object which holds zero elements.

提交回复
热议问题