Below is a Java program that finds the second-largest and second-smallest elements in an ArrayList of integers:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class SecondLargestSmallest {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(5);
numbers.add(20);
numbers.add(15);
numbers.add(25);
int secondLargest = findSecondLargest(numbers);
int secondSmallest = findSecondSmallest(numbers);
System.out.println("List: " + numbers);
System.out.println("Second Largest: " + secondLargest);
System.out.println("Second Smallest: " + secondSmallest);
}
public static int findSecondLargest(List<Integer> numbers) {
Collections.sort(numbers);
return numbers.get(numbers.size() - 2);
}
public static int findSecondSmallest(List<Integer> numbers) {
Collections.sort(numbers);
return numbers.get(1);
}
}
Explanation:
- We define a class called SecondLargestSmallest.
- In the main method, we create an ArrayList called numbers containing some integers. You can modify this list with your desired input elements.
- We call two methods, findSecondLargest and findSecondSmallest, to get the second-largest and second-smallest elements from the numbers list.
- Both methods use Collections.sort() to sort the list in ascending order. After sorting, the second-largest element will be at the index (numbers.size() - 2), and the second-smallest element will be at index 1.
- The findSecondLargest method returns the second-largest element, and the findSecondSmallest method returns the second-smallest element.
- Finally, the main method prints the original list and the second-largest and second-smallest elements.
Output will be:
List: [10, 5, 20, 15, 25]
Second Largest: 20
Second Smallest: 10
Please note that if the list contains duplicate elements, the program considers the second-largest and second-smallest elements without eliminating duplicates. For instance, in the above example, there are two occurrences of 20 (the largest element), but we still consider 20 as the second-largest element. Similarly, there are two occurrences of 10 (the smallest element), but we still consider 10 as the second-smallest element.
0 Comments