简体   繁体   English

有没有更好的逻辑可以在while循环中检查null?

[英]Any better logic available to check null in while loop?

Here is my code: 这是我的代码:

while (itr.hasNext()) {
    System.out.println(itr.next());
}

itr is type of Iterator . itrIterator类型。

If itr is null , then I'm facing null pointer exception. 如果itrnull ,那么我将面临null指针异常。

I've tried using if condition to check if the itr is not null before while loop . 我尝试使用if condition检查while loop之前itr是否不为null

Like below: 如下所示:

if (itr != null) {
    while (itr.hasNext()) {
        System.out.println(itr.next());
    }
}

Is there an other better way to do it? 还有其他更好的方法吗?

The code you are using will throw Null Pointer exception only if you deliberately assign null to Iterator. 仅当您故意为Iterator分配null时,您使用的代码才会引发Null Pointer异常。 For eg. 例如。 Below code will not throw an exception even if the exampleList has not been assigned any elements. 即使没有为exampleList分配任何元素,下面的代码也不会引发异常。

List<String> exampleList = new ArrayList<String>();

Iterator<String> itr = exampleList.iterator();

while (itr.hasNext()) {
   System.out.println(itr.next());
}

But below code will throw a null pointer exception as you are trying to create iterator on Null list. 但是下面的代码将在您尝试在Null列表上创建迭代器时引发空指针异常。

List<String> exampleList = null;         
Iterator<String> itr = exampleList.iterator();

while (itr.hasNext()) {
   System.out.println(itr.next());
}

Please check your code if you are initializing the list on which you are creating the iterator. 如果要初始化要在其上创建迭代器的列表,请检查代码。 If you are doing it properly, then there is no need to check for Null pointer. 如果操作正确,则无需检查Null指针。

Your approach seems better, but here is an another way to do it: 您的方法似乎更好,但这是另一种方法:

while (itr != null && itr.hasNext()) {
    System.out.println(itr.next());
}

u may also try inverse loop: 您也可以尝试反向循环:

if (null != itr && itr.hasNext()) {
  do {
    System.out.println(itr.next());
  } while (itr.hasNext());
}

Just to throw another answer into the mix, for variety: 只是为了混合而提出另一个答案:

while(Optional.ofNullable(itr).orElse(EmptyIterator.INSTANCE).hasNext()) {
    System.out.println(itr.next());
}

Or maybe: 或者可能:

Optional.ofNullable(itr).map(item -> {
    while(item.hasNext()) {
        System.out.println(item.next());
    }
});

Now sure how the .map will handle the println void return, though. 现在,请确保.map将如何处理println void返回。

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

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