Spaces:
Running
Running
someMethod(ArrayList<Integer> list)
Browse files
Week 3: Objects, files and exceptions/3a. Objects as parameters and return values
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Objects as parameters -> passed as a REFERENCE
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
so
|
| 5 |
+
a method can change/MODIFY INPLACE the input list it receives as a parameter
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
import java.util.ArrayList;
|
| 9 |
+
|
| 10 |
+
public class Example {
|
| 11 |
+
public static void main(String[] parameters){
|
| 12 |
+
ArrayList<Integer> numbers = new ArrayList<>();
|
| 13 |
+
for (int i=1; i<5; i++) {
|
| 14 |
+
numbers.add(i);
|
| 15 |
+
}
|
| 16 |
+
System.out.println(numbers);
|
| 17 |
+
increase(numbers);
|
| 18 |
+
System.out.println(numbers);
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
public static void increase(ArrayList<Integer> list) {
|
| 22 |
+
for (int i=0; i<list.size(); i++) {
|
| 23 |
+
list.set(i, list.get(i) + 1);
|
| 24 |
+
}
|
| 25 |
+
}
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
Program outputs:
|
| 29 |
+
[1, 2, 3, 4]
|
| 30 |
+
[2, 3, 4, 5]
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
|