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)
{
ArrayList
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)
{
ArrayList
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
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started