Consider the following Java code:
import java.util.ArrayList;
public class ArrayListOperations {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(5);
numbers.add(7);
numbers.add(4);
numbers.add(1);
numbers.add(9);
System.out.println("Original list: " + numbers);
numbers.set(2, 6);
numbers.remove(3);
numbers.add(8);
System.out.println("Updated list: " + numbers);
System.out.println("Sum of the numbers in the list: " + calculateSum(numbers));
System.out.println("Largest number in the list: " + findLargest(numbers));
System.out.println("Smallest number in the list: " + findSmallest(numbers));
System.out.println("Average of the numbers in the list: " + calculateAverage(numbers));
}
// Method to calculate the sum of numbers in the list
public static int calculateSum(ArrayList<Integer> list) {
int sum = 0;
for (int num : list) {
sum += num;
}
return sum;
}
// Method to find the largest number in the list
public static int findLargest(ArrayList<Integer> list) {
int largest = Integer.MIN_VALUE;
for (int num : list) {
if (num > largest) {
largest = num;
}
}
return largest;
}
// Method to find the smallest number in the list
public static int findSmallest(ArrayList<Integer> list) {
int smallest = Integer.MAX_VALUE;
for (int num : list) {
if (num < smallest) {
smallest = num;
}
}
return smallest;
}
// Method to calculate the average of numbers in the list
public static double calculateAverage(ArrayList<Integer> list) {
int sum = calculateSum(list);
return (double) sum / list.size();
}
}
The output of the above Java code will be:
Original list: [5, 7, 4, 1, 9]
Updated list: [5, 7, 6, 9, 8]
Sum of the numbers in the list: 35
Largest number in the list: 9
Smallest number in the list: 5
Average of the numbers in the list: 7.0
Explanation:
The given code demonstrates various methods and operations that can be performed on an ArrayList
in Java. Here's a step-by-step breakdown of the code:
ArrayList
called numbers
is created to store integers.add()
method is used to add integers to the numbers
list: 5, 7, 4, 1, and 9.println()
method is used to print the original list: [5, 7, 4, 1, 9]
.set()
method is used to replace the element at index 2 with the value 6.remove()
method is used to remove the element at index 3.add()
method is used to add the value 8 to the end of the list.println()
method is used to print the updated list: [5, 7, 6, 9, 8]
.calculateSum()
method is called to calculate the sum of the numbers in the list, which returns 35.findLargest()
method is called to find the largest number in the list, which returns 9.findSmallest()
method is called to find the smallest number in the list, which returns 5.calculateAverage()
method is called to calculate the average of the numbers in the list, which returns 7.0.Finally, the respective values are printed using the println()
method.