Spaces:
Running
Running
| 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 | |