对于空列表中的每个循环 [英] For each loop in the null list

查看:108
本文介绍了对于空列表中的每个循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们在一个空集合中执行一个foreach循环,则将不执行任何操作.但是,当集合为null时,该结构应该如何工作?

If we do a foreach loop in an empty collection, simply no actions will be taken. But how should work the structure in the case, when the collection is null?

Collection<String> c=null;
....
for(String item:c){
   println(item);
}

我可以运行代码并查看null引用异常.但是,确切的行为应该是什么呢?我找不到与此有关的任何手册页.

I can run the code and see the null reference exception. But what should be the behaviour exactly? I can't find any manual page about that.

我知道在标头上引发了异常,因为该集合为null.但是我想知道如何引发异常.可以通过if或Objects.requireNonNull()或其他某种方式完成,也可以按照David的回答所示.

I know that the exception is thrown at the header, because the collection is null. But I want to know HOW the exception is thrown. It could be done by if, or by Objects.requireNonNull(), or in some other ways, or as it is shown in the David's answer.

推荐答案

编译后的增强功能(或foreach)使用Iterator来迭代

A enhanced for (or foreach) after compilation uses under the hood an Iterator to iterate on the collection as stated by the JLS :

增强的for语句等效于的基本for语句 表格:

The enhanced for statement is equivalent to a basic for statement of the form:


for (I #i = Expression.iterator(); #i.hasNext(); ) {
    {VariableModifier} TargetType Identifier =
        (TargetType) #i.next();
    Statement
}

您可以通过编译后查看循环的反汇编代码(javap -c)来检查自己:

You can check if yourself by looking the disassembled code of your loop after compilation (javap -c) :


  3: invokeinterface #2,  1            // InterfaceMethod java/util/Collection.iterator:()Ljava/util/Iterator;
  8: astore_2
  9: aload_2
 10: invokeinterface #3,  1            // InterfaceMethod java/util/Iterator.hasNext:()Z
 15: ifeq          38
 18: aload_2
 19: invokeinterface #4,  1            // InterfaceMethod java/util/Iterator.next:()Ljava/lang/Object;
 24: checkcast     #5                  // class java/lang/String
 27: astore_3
 28: getstatic     #6                  // Field java/lang/System.out:Ljava/io/PrintStream;
 31: aload_3
 32: invokevirtual #7                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
 35: goto          9

所以,就像您写过一样:

So, it is like if you had written :

Collection<String> c = null;
for (Iterator<String> iterator = c.iterator(); iterator.hasNext();) {
    String item = iterator.next();          
}

null上调用iterator()会引发NullPointerException.

这篇关于对于空列表中的每个循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆