Java中空字符串的split方法获取到长度为1的字符串数组的原因解析
今天在写项目的过程中发现一个问题,想要从文件中获取一个值时我们往往会使用读取整行的方法,如果有多个同类数据需要读取的时候,我自然而然地想到了String的.split方法,在同一行中写入多个数据,并使用该方法分离为数组。
但是奇怪的是,当我尝试给出一个空行的时候,返回的却不是一个空数组而是一个长度为一的,包含了一个空字符串的数组。
按照常理来说,对一个空字符串进行split,得到的理应是不含任何元素的空数组,那为什么会出现这样的现象呢?
查看String的split方法可知
public String[] split(String regex, int limit) {
/* fastpath if the regex is a
* (1) one-char String and this character is not one of the
* RegEx's meta characters ".$|()[{^?*+\\", or
* (2) two-char String and the first char is the backslash and
* the second is not the ascii digit or ascii letter.
*/
char ch = 0;
if (((regex.length() == 1 &&
".$|()[{^?*+\\".indexOf(ch = regex.charAt(0)) == -1) ||
(regex.length() == 2 &&
regex.charAt(0) == '\\' &&
(((ch = regex.charAt(1))-'0')|('9'-ch)) < 0 &&
((ch-'a')|('z'-ch)) < 0 &&
((ch-'A')|('Z'-ch)) < 0)) &&
(ch < Character.MIN_HIGH_SURROGATE ||
ch > Character.MAX_LOW_SURROGATE))
{
int off = 0;
int next = 0;
boolean limited = limit > 0;
ArrayList<String> list = new ArrayList<>();
while ((next = indexOf(ch, off)) != -1) {
if (!limited || list.size() < limit - 1) {
list.add(substring(off, next));
off = next + 1;
} else { // last one
//assert (list.size() == limit - 1);
int last = length();
list.add(substring(off, last));
off = last;
break;
}
}
// 看此处的代码,当字符串匹配不到分隔符的时候,Java选择了创建一个新字符串数组并将当前字符串(对于此处来说也就是空字符串)塞进去。
if (off == 0)
return new String[]{this};
// Add remaining segment
if (!limited || list.size() < limit)
list.add(substring(off, length()));
由此,我们便可以理解为什么会返回一个长度为一的数组的原因。
采用这种方法,split方法便可以将不含分隔符的字符串整体返回,但是同时也导致了预期返回空数组但是却返回了一个长度为一的字符串数组的问题。