Question: You can also use a while or for loop to process list elements using the index. The ArrayList index starts at 0 just like arrays,

You can also use a while or for loop to process list elements using the index. The ArrayList index starts at 0 just like arrays, but instead of using the square brackets [] to access elements, you use the get(index) to get the value at the index and set(index,value) to set the element at an index to a new value. If you try to use an index that is outside of the range of 0 to the number of elements 1 in an ArrayList, your code will throw an ArrayIndexOutOfBoundsException, just like in arrays.

importjava.util.*;

publicclassTestForLoop

{

publicstaticvoidmain(String[]args)

{

ArrayListmyList=newArrayList();

myList.add(50);

myList.add(30);

myList.add(20);

inttotal=0;

for(inti=0;i<=myList.size();i++)

{

total=total+myList.get(i);

}

System.out.println(total);

}

}

Question 2. What does the following code do? Guess before you run it. Then, add another enhanced for each loop that computes the product of all the elements in myList by multiplying them. Print out the product after the new loop. importjava.util.*; //importallclassesinthispackage.

publicclassTest1

{

publicstaticvoidmain(String[]args)

{

ArrayListmyList=newArrayList();

myList.add(50);

myList.add(30);

myList.add(20);

inttotal=0;

for(Integervalue:myList)

{

total+=value;

}

System.out.println("Sumofallelements:"+total);

//Writeafor-eachloopthatcomputestheproduct

//ofalltheelementsinmyListandprintouttheproduct.

}

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!