Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 增强的for循环是否应该包含一个返回列表的函数_Java_For Loop - Fatal编程技术网

Java 增强的for循环是否应该包含一个返回列表的函数

Java 增强的for循环是否应该包含一个返回列表的函数,java,for-loop,Java,For Loop,我只是关心直接调用方法的增强for循环。 代码中嵌套的是我的问题(大写): public class ExtendedForLoop { public static List<Integer> returnList() { System.out.println("Hurray ----> "); List<Integer> abc = new ArrayList<Integer>(); abc.a

我只是关心直接调用方法的增强for循环。 代码中嵌套的是我的问题(大写):

public class ExtendedForLoop {

    public static List<Integer> returnList() {
        System.out.println("Hurray ----> ");
        List<Integer> abc = new ArrayList<Integer>();
        abc.add(5);
        abc.add(10);
        abc.add(20);
        return abc;
    }

    public static void main(String args[]) {
        for (Integer i : returnList()) { // <----- OPTION 1. Include function call in extended loop.
            System.out.println(i);
        }

        List<Integer> list  = returnList()
        for (Integer i : list) { // <----- OPTION 2. Provide list to function call.
            System.out.println(i);
        }
    }
}
公共类扩展ForLoop{
公共静态列表returnList(){
System.out.println(“Hurray-->”);
List abc=new ArrayList();
abc.add(5);
abc.add(10);
abc.add(20);
返回abc;
}
公共静态void main(字符串参数[]){

对于(Integer i:returnList()){/我认为使用
null检查的第二种方法更安全


如果方法返回
null

那么增强for循环将通过
NullPointerException
实现。如果您正在处理NullPointerException,那么我更愿意使用选项1,因为我们正在创建一个额外变量“列表”在堆栈上会占用一些内存,这也会使性能降低一些位。

如果我是返回列表的代码的所有者,并且可以保证永远不会返回null,我更喜欢使用选项1

如果我不是所有者,我更喜欢使用不同的构造

for(Integer i : guaranteeCollection(resultList()) { // dostuff } 对于(整数i:GuaranteCollection(resultList()) { //多斯塔夫 } 公共静态和ltT>收集和ltT>担保收集(收集和ltT>c) { 返回c!=null?c:Collections.EMPTY_LIST; }
这可以避免在代码中创建不必要的变量声明,并防止NPE。

这取决于您的系统设计:

许多项目目标避免空对象


如果您确定
returnList()
永远不会返回
null
(它应该返回一个空列表(或
Collections.emptyList
),然后选择解决方案1,以其他方式选择解决方案2。

除非您处理的代码超出了您的控制,否则在返回
集合的方法中返回
null
真的很难看!我不是downvoter。“堆栈”上的变量我想这是我们最不需要担心的事情之一。方法一完成,它们就会消失。是的@Nambari dat这就是为什么我说如果他正在处理nullpointerexception,那么选项1和2都是相同的。我们应该尽量减少不必要变量的创建。 public static <T> Collection<T> guaranteeCollection(Collection<T> c) { return c != null ? c : Collections.EMPTY_LIST; }