Spaces:
Running
Running
eg change order
Browse files
Week 3: Objects, files and exceptions/5a. Method side effects
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Avoid changing input object in a method
|
| 2 |
+
|
| 3 |
+
eg
|
| 4 |
+
ordering the list by size using the sort method in the Collections class:
|
| 5 |
+
public static int secondSmallest(ArrayList<Integer> numbers) {
|
| 6 |
+
Collections.sort(numbers);
|
| 7 |
+
return (numbers.get(1));
|
| 8 |
+
}
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
The method itself does produce the correct result, but it also AFFECTS the ORDER of the list:
|
| 14 |
+
|
| 15 |
+
import java.util.ArrayList;
|
| 16 |
+
import java.util.Collections;
|
| 17 |
+
|
| 18 |
+
public 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 |
+
|
| 38 |
+
Program outputs:
|
| 39 |
+
List before: [5, 1, 8, 3, 7]
|
| 40 |
+
Second smallest: 3
|
| 41 |
+
List after: [1, 3, 5, 7, 8]
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
CHANGE = SIDE EFFECT
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
|