Use of array of zero length

后端 未结 3 1236
梦毁少年i
梦毁少年i 2020-11-28 10:19

For example we can construct such an array like this:

 new ElementType[0];

I seen such a construct, but I don\'t understand why this might

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-28 10:56

    It's easier to work with than null in many cases, where null is the obvious alternative.

    Suppose you want to return an Iterable containing (say) a list of relevant filenames... but there aren't any for some reason. You could return null to indicate that, but then the caller has to special-case that. Instead, if you return an empty collection, the caller can still use an enhanced for loop:

    for (String file : getFiles())
    

    So why use an empty array instead of an empty ArrayList or something similar? Arrays are a fixed size, so an empty array is effectively immutable. That means you can keep a single value and return it to whoever you like, knowing they can't possibly do anything with it. That can be very useful in some situations.

提交回复
热议问题