为什么 Java 允许大小为 0 的数组? [英] Why does Java allow arrays of size 0?

查看:44
本文介绍了为什么 Java 允许大小为 0 的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

java 中的数组长度是固定的.为什么 Java 允许大小为 0 的数组呢?

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

String[] strings = new String[0];

推荐答案

表示为空.IE.你可以循环它,就好像它有项目并且没有结果发生:

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
}

从而避免检查的需要.如果有问题的数组是 null,则会发生异常,但在这种情况下,它什么也不做,这可能是合适的.

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.

这篇关于为什么 Java 允许大小为 0 的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆