File size: 1,106 Bytes
1c011b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
Avoid changing input object in a method

eg
ordering the list by size using the sort method in the Collections class:
public static int secondSmallest(ArrayList<Integer> numbers) {
    Collections.sort(numbers);
    return (numbers.get(1));
}




The method itself does produce the correct result, but it also AFFECTS the ORDER of the list:

import java.util.ArrayList;
import java.util.Collections;

public class Example {
    public static void main(String[] args){
        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);   
    }

    public static int secondSmallest(ArrayList<Integer> numbers) {
        Collections.sort(numbers);
        return (numbers.get(1));
    }
}

Program outputs:
List before: [5, 1, 8, 3, 7]
Second smallest: 3
List after: [1, 3, 5, 7, 8]




CHANGE = SIDE EFFECT