java 如何为每个循环填写一个 ArrayList?(爪哇)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29543889/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 15:28:20  来源:igfitidea点击:

How to fill out an ArrayList with for each loop? (Java)

java

提问by Ronny McNamara

I have to fill in an ArrayList with the first 10 multiples of two using a for each loop. I really can't seem to figure out how and I can't use any other loops.

我必须在每个循环中使用 2 的前 10 个倍数填充一个 ArrayList。我似乎真的无法弄清楚如何使用任何其他循环。

Here is my code which is not working.

这是我的代码不起作用。

   ArrayList<Integer> arraylist = new ArrayList<Integer>(10);  
   for (Integer y : arraylist) {
         arraylist.add( (2+(y*2)));      
   }

采纳答案by Makoto

I'll address the point that everyone here is mostly glossing over: there is a key difference between a normal forstatement and the enhanced-forstatement.

我将解决这里每个人都在掩饰的一点:普通for语句和增强for语句之间存在关键区别。

The enhanced-foris defined in the JLSas syntactic sugar. What kindof sugar you get depends on what you're iterating over.

增强for的-在 JLS 中定义为语法糖。你得到什么的糖取决于你在迭代什么。

  • If you're iterating over an Iterablelike an ArrayList, it is using the Iteratorfrom that entity.

    for(I #i=Expression.iterator(); #i.hasNext();){
        VariableModifiersopt TargetType Identifier=
        (TargetType) #i.next();
        Statement
    }
    
  • If you're iterating over an array, then it's shorthand for the common forstatements one is accustomed to doing.

    T[] #a = Expression;
    L1: L2: ... Lm:
    for (int #i = 0; #i < #a.length; #i++) {
        VariableModifiersopt TargetType Identifier = #a[#i];
        Statement
    }
    
  • 如果您正在迭代Iterable类似 an ArrayList,则它正在使用Iterator来自该实体的 。

    for(I #i=Expression.iterator(); #i.hasNext();){
        VariableModifiersopt TargetType Identifier=
        (TargetType) #i.next();
        Statement
    }
    
  • 如果您正在迭代一个数组,那么它for是人们习惯做的常见语句的简写。

    T[] #a = Expression;
    L1: L2: ... Lm:
    for (int #i = 0; #i < #a.length; #i++) {
        VariableModifiersopt TargetType Identifier = #a[#i];
        Statement
    }
    

Thus, the enhanced-forhas one assumption:

因此,增强型-for有一个假设:

What you're iterating over must be a non-empty collection or array.

您要迭代的内容必须是非空集合或数组。

The statement is only meant to iterate over existingelements, not provide a way or interface to iteratively add new elements.

该语句仅用于迭代现有元素,不提供迭代添加新元素的方法或接口。

There are any number of ways to sort this out, but the simplest is the most common approach: use a forstatement.

有很多方法可以解决这个问题,但最简单的是最常见的方法:使用for语句。

ArrayList<Integer> arraylist = new ArrayList<Integer>(10);  
for (int i = 0; i < 10; i++) {
    arraylist.add( (2+(i*2)));      
}

回答by nucandrei

The solution is simple

解决方法很简单

final int[] numbers = new int[] {2,4,6,8,10,12,14,16,18,20};
final List<Integer> list = new ArrayList<Integer>();
for (int number : numbers) {
    list.add(number);
}

回答by Paul

Your loop loops over all values in arrayListsince it's empty, the part in the loop is actually never running. Use

您的循环遍历所有值,arrayList因为它是空的,循环中的部分实际上从未运行。利用

for(int i = 0 ; i < 10 ; i++)
     arrayList.add(2 * (i + 1));

instead

反而

回答by Bubletan

Something like this maybe?

也许像这样的东西?

IntStream.range(0, 10).map(y -> 2 + y * 2).forEach(arraylist::add);

回答by Prem

Unlike arrays, ArrayList won't be initialized with objects. So the size of the ArrayList will be zero after the initialization. One work around is to create the list from Arrays as below: (But this is only a work around). But even in this case, the List will be initialized with nulls, not with 0s. So the y will be null.

与数组不同,ArrayList 不会用对象初始化。所以初始化后ArrayList的大小将为零。一种解决方法是从数组创建列表,如下所示:(但这只是一种解决方法)。但即使在这种情况下,List 也将使用空值而不是 0 进行初始化。所以 y 将为空。

List<Integer> arraylist = Arrays.asList(new Integer[10]);
        //Collections.fill(arraylist, new Integer(1));
        System.out.println(arraylist);
        int i=0;
        for (Integer y : arraylist) {
             //System.out.println( (2+(y*2)));
             arraylist.set(i++, ((i*2)));      
       }

回答by gilleain

What about :

关于什么 :

int[] values = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for (int i : values) { list.add(i * 2); }

(stolen from a comment! :) )

(从评论中窃取!:))

回答by Jean-Fran?ois Savard

You are creating the ArrayListwith 10 as constructor parameters, which define it initial capacity (which is already 10 by default btw), but does not set any value. In other words, you try to iterate on an empty list, hence never enter it.

您正在创建ArrayList10 作为构造函数参数,它定义了它的初始容量(顺便说一句,默认情况下已经是 10),但没有设置任何值。换句话说,您尝试迭代一个空列表,因此永远不要输入它。

You can't achieve this with a for-each, you could achieve this with a for.

你不能用 afor-each来实现这一点,你可以用 a 来实现for

final List<Integer> myList = new ArrayList<>();
for(int i = 1; i <= 10; i++)
   myList.add(2 * i);