Iterating through a variable length array

前端 未结 4 1441
囚心锁ツ
囚心锁ツ 2020-12-03 13:54

How do I iterate over a Java array of variable length.

I guess I would setup a while loop, but how would I detect that I have reached the end of the array.

4条回答
  •  囚心锁ツ
    2020-12-03 14:04

    here is an example, where the length of the array is changed during execution of the loop

    import java.util.ArrayList;
    public class VariableArrayLengthLoop {
    
    public static void main(String[] args) {
    
        //create new ArrayList
        ArrayList aListFruits = new ArrayList();
    
        //add objects to ArrayList
        aListFruits.add("Apple");
        aListFruits.add("Banana");
        aListFruits.add("Orange");
        aListFruits.add("Strawberry");
    
        //iterate ArrayList using for loop
        for(int i = 0; i < aListFruits.size(); i++){
    
            System.out.println( aListFruits.get(i) + " i = "+i );
             if ( i == 2 ) {
                    aListFruits.add("Pineapple");  
                    System.out.println( "added now a Fruit to the List "); 
                    }
            }
        }
    }
    

提交回复
热议问题