简体   繁体   中英

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 .

If itr is null , then I'm facing null pointer exception.

I've tried using if condition to check if the itr is not null before while loop .

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. For eg. Below code will not throw an exception even if the exampleList has not been assigned any elements.

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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