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.
Here is my code which is not working.
ArrayList<Integer> arraylist = new ArrayList<Integer>(10);
for (Integer y : arraylist) {
arraylist.add( (2+(y*2)));
}
I'll address the point that everyone here is mostly glossing over: there is a key difference between a normal for
statement and the enhanced-for
statement.
The enhanced-for
is defined in the JLS as syntactic sugar. What kind of sugar you get depends on what you're iterating over.
If you're iterating over an Iterable
like an ArrayList
, it is using the Iterator
from 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 for
statements 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
}
Thus, the enhanced-for
has one assumption:
The statement is only meant to iterate over existing elements, 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 for
statement.
ArrayList<Integer> arraylist = new ArrayList<Integer>(10);
for (int i = 0; i < 10; i++) {
arraylist.add( (2+(i*2)));
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句