CoolFace
Apppublic

KaiquanMah/TurkuBasicOOPinJava

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
5a. Method side effects52 linesDownload Raw Back to Week 3: Objects, files and exceptions
1Avoid changing input object in a method2 3eg4ordering the list by size using the sort method in the Collections class:5public static int secondSmallest(ArrayList<Integer> numbers) {6    Collections.sort(numbers);7    return (numbers.get(1));8}9 10 11 12 13The method itself does produce the correct result, but it also AFFECTS the ORDER of the list:14 15import java.util.ArrayList;16import java.util.Collections;17 18public class Example {19    public static void main(String[] args){20        ArrayList<Integer> numbers = new ArrayList<>();21        numbers.add(5);22        numbers.add(1);23        numbers.add(8);24        numbers.add(3);25        numbers.add(7);26 27        System.out.println("List before: " + numbers);28        System.out.println("Second smallest: " + secondSmallest(numbers));29        System.out.println("List after: " + numbers);   30    }31 32    public static int secondSmallest(ArrayList<Integer> numbers) {33        Collections.sort(numbers);34        return (numbers.get(1));35    }36}37 38Program outputs:39List before: [5, 1, 8, 3, 7]40Second smallest: 341List after: [1, 3, 5, 7, 8]42 43 44 45 46CHANGE = SIDE EFFECT47 48 49 50 51 52