Why does Java allow arrays of size 0?

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

    It signifies that it is empty. I.e. you can loop over it as if it had items and have no result occur:

    for(int k = 0; k < strings.length; k++){
       // something
    }
    

    Thereby avoiding the need to check. If the array in question were null, an exception would occur, but in this case it just does nothing, which may be appropriate.

提交回复
热议问题