TurkuBasicOOPinJava / Week 3: Objects, files and exceptions /5b. Second smallest without side effects
KaiquanMah's picture
Collections.min/max, THEN go through list to find secondSmallest
e0149bd verified
raw
history blame
2.2 kB
Write the method
int secondSmallest(ArrayList<Integer> numbers)
...which returns the second smallest element in the list.
The method must not change the order of the elements in the list.
Example method call:
public static void main(String[] parameters){
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(5);
numbers.add(1);
numbers.add(8);
numbers.add(3);
numbers.add(7);
System.out.println("List before: " + numbers);
System.out.println("Second smallest: " + secondSmallest(numbers));
System.out.println("List after: " + numbers);
}
Program outputs:
List before: [5, 1, 8, 3, 7]
Second smallest: 3
List after: [5, 1, 8, 3, 7]
import java.util.Random;
import java.util.ArrayList;
import java.util.Collections;
public class Test{
public static void main(String[] args){
final Random r = new Random();
int[][] s = {{3,2,1,4}, {10,20,40,50,30,60}, {9,7,5,3,8,6,4,2}, {25,5,20,15,10}};
for (int[] pa : s) {
ArrayList<Integer> lista = new ArrayList<>();
for (int l : pa) lista.add(l);
System.out.println("List before: ");
System.out.println("" + lista);
System.out.println("Second smallest: " + secondSmallest(lista));
System.out.println("List after: ");
System.out.println(lista);
System.out.println("");
}
}
//ADD
public static int secondSmallest(ArrayList<Integer> numbers){
int smallest = Collections.min(numbers);
int secondSmallest = Collections.max(numbers);
for (int i : numbers) {
if (i > smallest && i < secondSmallest) {
secondSmallest = i;
}
}
return secondSmallest;
}
}
List before:
[3, 2, 1, 4]
Second smallest: 2
List after:
[3, 2, 1, 4]
List before:
[10, 20, 40, 50, 30, 60]
Second smallest: 20
List after:
[10, 20, 40, 50, 30, 60]
List before:
[9, 7, 5, 3, 8, 6, 4, 2]
Second smallest: 3
List after:
[9, 7, 5, 3, 8, 6, 4, 2]
List before:
[25, 5, 20, 15, 10]
Second smallest: 10
List after:
[25, 5, 20, 15, 10]