String为空时,使用spilt分割出的数组,为什么长度是1,不应该是0吗????

天台的狗 2018-06-07 11:03:22
public static void main(String[] args){

String string = "";
String[] array = string.split(",");

System.out.println("数组的大小:"+array.length);
System.out.println("数组的第一个元素:"+array[0]);

}


结果:
数组的大小:1
数组的第一个元素:



...全文
1781 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
stacksoverflow 2018-06-07
  • 打赏
  • 举报
回复
参照String源代码2250-2252行 (jdk1.8.0_171) If the expression does not match any part of the input then the resulting array has just one element, namely this string. 如果没有匹配到任何字符,则返回他自己。 空字符串属于上面的情况。 参照String源代码2363,2364行 (jdk1.8.0_171) if (off == 0) return new String[]{this}; 第二个参数limit默认值为0,意思是match后的所有空字符串,但这属于没有match的情况,命中了上面的case,所以返回自己,长度为1的空字符串。 有人提交过JDK的BUG,被认为不是BUG,参照如下: 参照:https://bugs.openjdk.java.net/browse/JDK-8020672 This is not a bug. The spec states that: If the expression does not match any part of the input then the resulting array has just one element, namely this string. In this case " ".split( " , " , 0) - there is no matching pattern and thus it returns the original string " ".
AMX50B 2018-06-07
  • 打赏
  • 举报
回复
“”和null是有区别的,“”会在常量池开辟空间,他也是一个字符串

50,523

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧