Java String.split是否可以返回null String [] [英] Is it possible that Java String.split can return a null String[]

查看:446
本文介绍了Java String.split是否可以返回null String []的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

split 是否可以返回null String [] ?我很好奇,因为我想在我的代码中尽可能保持防御,而不必进行不必要的检查。代码如下:

Is it possible for split to return a null String[]? I am curious as I want to try to be as defensive as possible in my code without having unnecessary checks. The code is as follows:

String[] parts = myString.split("\\w");  

我需要在使用部件 post splitting?

do I need to perform a null check before I use parts post splitting?

推荐答案

它永远不会返回null。如果您不确定,应该始终检查方法的javadoc。例如, String#split(String)

It never returns null. You should always check the javadoc of the method if you are not sure. For example String#split(String) says


此方法就好像通过调用双参数拆分方法

...和 String#split(String,int) 说:

...and String#split(String,int) says:


如果表达式不匹配输入的任何部分,那么结果数组只有一个元素,即这个字符串。

If the expression does not match any part of the input then the resulting array has just one element, namely this string.

从Javadoc你也可以找到可以发生什么样的异常,更重要的是为什么抛出这些异常。另外一个非常重要的事情是检查类是否是线程安全的。

From Javadoc you can also find out what kind of exceptions can happen and more importantly why were those exceptions thrown. Also one very important thing to check is if the classes are thread safe or not.

这篇关于Java String.split是否可以返回null String []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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