Why does Java allow arrays of size 0?

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

    Consider this (a more detailed explanation of Noon's answer):

    public String[] getStrings() {
     if( foo ) {
      return null;
     } else {
      return new String[] {"bar, "baz"};
     }
    }
    
    String[] strings = getStrings();
    if (strings != null) {
     for (String s : strings) {
      blah(s);
     }
    }
    

    Now compare it to this:

    public String[] getStrings() {
     if( foo ) {
      return new String[0];
     } else {
      return new String[] {"bar, "baz"};
     }
    }
    
    // the if block is not necessary anymore
    String[] strings = getStrings();
    for (String s : strings) {
     blah(s);
    }
    

    This (returning empty arrays rather than null values), is in fact a best practice in Java API design world.

    Besides, in Java, you can covert Lists (e.g. ArrayList) to arrays and it only makes sense to convert an empty list to an empty array.

提交回复
热议问题