Java ListIterator.next() 返回 null
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24912785/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ListIterator.next() returns null
提问by dexBerlin
my question is really, really simple, but everything I find online tells me I am doing it the right way - but I obviously misunderstood something.
我的问题真的非常简单,但我在网上找到的一切都告诉我我的做法是正确的——但我显然误解了一些东西。
I have a simple, simple Java ListIterator, which in a while-hasNext()-loop returns a null for next(). Here's the code with my comments on the debug state:
我有一个简单的 Java ListIterator,它在 while-hasNext() 循环中为 next() 返回一个 null。这是我对调试状态的评论的代码:
[...]
ListIterator<Role> rolesIterator = currentUser.getRoles().listIterator();
// rolesIterator is now: java.util.ArrayList$ListItr
while( rolesIterator.hasNext() ) {
Role roleObject = rolesIterator.next(); // extra step for debugging reasons
String role = roleObject.getName(); // NullPointerException - roleObject is null
[...]
In my thoughts, the loop should not be entered, if there is no next() object - that's why I check using hasNext(). What did I understand wrong, and what is the correct way?
在我看来,如果没有 next() 对象,则不应进入循环——这就是我使用 hasNext() 检查的原因。我理解错了什么,正确的方法是什么?
采纳答案by JB Nizet
There is a next element in the list, and this next element happens to be null. For example:
列表中有一个下一个元素,而这个下一个元素恰好为空。例如:
List<String> list = new ArrayList<>();
list.add("foo");
list.add(null);
list.add("bar");
The above list has 3 elements. The second one is null.
上面的列表有 3 个元素。第二个是空的。
Fix the code that populates the list and make sure it doesn't add any null Role in the list, or check for null inside the loop to avoid NullPointerExceptions.
修复填充列表的代码并确保它不会在列表中添加任何 null 角色,或者检查循环内的 null 以避免 NullPointerExceptions。
回答by Jama Djafarov
I believe list can contain null values. so the roleObject can be null.
我相信列表可以包含空值。所以 roleObject 可以为空。
I prefer the for loop approach (cleaner):
我更喜欢 for 循环方法(更干净):
for (Role roleObject : currentUser.getRoles()) {
...
}
回答by Azar
ListIterator
documentation states that next()
:
ListIterator
文件指出next()
:
Throws: NoSuchElementException - if the iteration has no next element
抛出: NoSuchElementException - 如果迭代没有下一个元素
Furthermore, you do the appropriate hasNext()
check as the loop condition. So the obvious conclusion is that currentUser.getRoles()
contains null
elements. To fix [this part of] your code:
此外,您可以进行适当的hasNext()
检查作为循环条件。所以显而易见的结论是currentUser.getRoles()
包含null
元素。要修复 [这部分] 您的代码:
while( rolesIterator.hasNext() ) {
Role roleObject = rolesIterator.next();
if(roleObject != null)
{
String role = roleObject.getName();
[...]
}