Question:
public class ArrayListIntro {
public static void main(String[] args) {
// Create an ArrayList of type Integer and name it 'numbers'
// Add the following numbers to the 'numbers' ArrayList: 4, 8, 2, 6, 10
// Write a method called 'getLargest' that takes an ArrayList of Integers as a parameter
// The method should find and return the largest number in the ArrayList.
// Test the 'getLargest' method by passing the 'numbers' ArrayList.
// Print the returned value and verify if it is correctly finding the largest number.
}
// Write your 'getLargest' method here
}
Answer:
import java.util.ArrayList;
public class ArrayListIntro {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(4);
numbers.add(8);
numbers.add(2);
numbers.add(6);
numbers.add(10);
int largestNumber = getLargest(numbers);
System.out.println("The largest number in the 'numbers' ArrayList is: " + largestNumber);
}
public static int getLargest(ArrayList<Integer> list) {
int largest = list.get(0);
for (int i = 1; i < list.size(); i++) {
if (list.get(i) > largest) {
largest = list.get(i);
}
}
return largest;
}
}
Explanation:
In the given code, we start by creating an ArrayList of type Integer named numbers
. We then add the numbers 4, 8, 2, 6, and 10 to the numbers
ArrayList using the add()
method.
Next, we define a method called getLargest
that takes an ArrayList of Integers as a parameter. Within this method, we initialize a variable named largest
to store the largest number. We set largest
to the first element of the ArrayList using the get()
method.
We then loop through the rest of the ArrayList using a for loop starting at index 1. For each element, we compare it with the current largest number. If the element is greater than the current largest number, we update largest
to the new value.
Finally, we return the largest number from the method.
In the main()
method, we call the getLargest
method passing the numbers
ArrayList as an argument. The returned value is stored in the largestNumber
variable. We then print the value of largestNumber
to verify if the getLargest
method is correctly finding the largest number in the numbers
ArrayList.