How do I fill in an ArrayList for each loop? (JAVA)

I have to fill an ArrayList with the first 10 multiples of each loop I really can't seem to figure out how I can't use any other loops

This is my code invalid

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

Solution

I will address this, and everyone here is mostly hiding: there is a key difference between normal and enhanced statements

Enhanced is defined as in the JLS as a grammatical sugar What kind of sugar you get depends on what you are iterating over

>If you are iterating over an iteratable like ArrayList, it is using the iterator

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

>If you iterate over an array, it's short for the common for statement you're used to doing

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

Therefore, the enhanced model has a hypothesis:

The content you want to iterate over must be a non - empty collection or array

This statement is only used to iterate over existing elements, not to provide methods or interfaces for adding new elements iteratively

There are many ways to sort this, but the simplest way is to use the for statement

ArrayList<Integer> arraylist = new ArrayList<Integer>(10);  
for (int i = 0; i < 10; i++) {
    arraylist.add( (2+(i*2)));      
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>