英文:
cannot call items.isEmpty() after splitting an array
问题
我是一个初学者。为什么isEmpty()在我的问题中被定义为错误。
我修剪并分割一个字符串数组:
String[] items = s.trim().split("[ !,?.\\_'@]+");
我想要打印:
int i = (items.isEmpty()) ? 0 : items.length;
但是isEmpty显示为错误。
英文:
I am a beginner. Why isEmpty() is defined an error in my question.
I trim and split a string array:
String[] items = s.trim().split("[ !,?.\\_'@]+");
I want to print
int i = (items.isEmpty()) ? 0 : items.length;
but isEmpty shows an error.
答案1
得分: 2
数组没有isEmpty方法。 您需要使用items.length == 0自行检查。
此外,请注意items永远不会为空:
> 如果表达式与输入的任何部分都不匹配,则生成的数组只有一个元素,即此字符串。
英文:
Arrays don't have isEmpty method. You need to check it yourself with items.length == 0.
Also, be aware that items is never empty:
> If the expression does not match any part of the input then the resulting array has just one element, namely this string.
答案2
得分: 1
String[] items 被称为 数组,是 Java 中最简单的 数据结构 之一。还有一些更复杂和方便的数据结构,比如 ArrayList、HashMap 等。
isEmpty() 是一个在 List 接口 中声明的方法,因此所有实现了这个接口的 Java 类都有其 isEmpty 方法的实现。 (String[] 不是 List 的实现)
注意:split 方法始终会返回 非空数组,所以拥有一个像 isEmpty 这样的方法是无用的。你只需要检查返回值的长度,items.length == 0。
英文:
String[] items is known as an array and is one of the most simple data structures in Java. There are more complicated and handy data structures like ArrayList, HashMap, etc.
The isEmpty() is a method which has been declared in the List Interface, so all the Java classes that implemented this interface have their implementation of isEmpty method. (String[] is not an implementation of List)
Note: split method always returns a non-empty array, so it is useless to to have a method like isEmpty. You can just check the length of returned value, items.length == 0
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论