简体   繁体   English

Java列表 <String> 空时返回1

[英]Java List<String> returns 1 when empty

Why does the following code return 1 when I pass in an empty String ""? 当我传入空字符串“”时,以下代码为什么返回1?

private int GetItemsInCommaSeparatedList(){
    // Locals
    String param = ""; // "1,2,3" returns 3 without issue
    List<String> items = Arrays.asList(param.split("\\s*,\\s*"));

    // Empty?
    if ( items.isEmpty() )
        return 0;

    // Return
    return new items.size();
}

Javadoc to the rescue 抢救Javadoc

If the expression does not match any part of the input then the resulting array has just one element, namely this string. 如果表达式与输入的任何部分都不匹配,则结果数组只有一个元素,即此字符串。

Your regex doesn't match anything in the empty string and therefore the method returns an array containing one element, your empty string. 您的正则表达式与空字符串中的任何内容都不匹配,因此该方法返回一个包含一个元素(空字符串)的数组。

Empty string is element as well. 空字符串也是元素。 Just print content of list. 只需打印列表内容。

you are adding empty string to the list. 您正在将空字符串添加到列表中。

String param = ""; // "1,2,3" returns 3 without issue
List<String> items = Arrays.asList(param.split("\\s*,\\s*"));

That's why it returns 1 as size 这就是为什么它返回1作为大小

Your split delimiter \\\\s*,\\\\s* does not match the empty string, at the point, the resulting array has just one element, which is the string itself. 您的分隔定界符\\\\s*,\\\\s*与空字符串不匹配,此时,所得数组只有一个元素,即字符串本身。 If you want to return 0 for the empty String, try this: 如果要为空字符串返回0,请尝试以下操作:

private static int GetItemsInCommaSeparatedList(){

    String param = ""; // "1,2,3" returns 3 without issue
    Pattern p = Pattern.compile("\\s*,\\s*");
    Matcher m = p.matcher(param);
    List<String> items = new ArrayList<String>();
    if(m.find()){
        System.out.println("Found");
        items = Arrays.asList(param.split("\\s*,\\s*"));
    }

    if ( items.isEmpty() )
        return 0;
    return items.size();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM