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 []
发布评论