Is it possible that Java String.split can return a null String[]

对着背影说爱祢 提交于 2019-12-03 09:21:17
palto

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

This method works as if by invoking the two-argument split method

...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.

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.

I recommend you download the Java source code for those times when the API is unclear. All the answers here just tell you the answer but you should really see for yourself. You can download the Java source code from here (look near the bottom of the page).

By following the source code you'll end up at String[] Pattern.split(CharSequence input, int limit). The return value comes from a non-null ArrayList on which toArray is called. toArray does not return null: in the event of an empty list you'll get an empty array back.

So in the end, no, you don't have to check for null.

No, you don't need to check for null on the parts.

Split method calls the Patter.split method which does this in the beginning of the method:

ArrayList<String> matchList = new ArrayList<String>();

And at the end does matchList.toArray() to return an Array.

So no need to test of nulls.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!