Spaces:
Running
Running
ArrayList<String> list = new ArrayList<>();
Browse files
Week 3: Objects, files and exceptions/6a. Objects as return values
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
It is often better practice to CREATE a NEW OBJECT and RETURN it from the method.
|
| 2 |
+
In this case, the original object is not changed.
|
| 3 |
+
|
| 4 |
+
The normal way to return an object is with a return statement.
|
| 5 |
+
On the calling method side, the return value must of course be stored in a variable if it is to be used later in the program.
|
| 6 |
+
|
| 7 |
+
import java.util.ArrayList;
|
| 8 |
+
|
| 9 |
+
public class Example {
|
| 10 |
+
public static void main(String[] parameters){
|
| 11 |
+
ArrayList<Integer> numbers = new ArrayList<>();
|
| 12 |
+
numbers.add(5);
|
| 13 |
+
numbers.add(1);
|
| 14 |
+
numbers.add(8);
|
| 15 |
+
|
| 16 |
+
System.out.println("List before: " + numbers);
|
| 17 |
+
System.out.println("New list: " + increasebyOne(numbers));
|
| 18 |
+
System.out.println("List after: " + numbers);
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
public static ArrayList<Integer> increasebyOne(ArrayList<Integer> numbers) {
|
| 22 |
+
ArrayList<Integer> newList = new ArrayList<>();
|
| 23 |
+
for (int element : numbers) {
|
| 24 |
+
newList.add(element + 1);
|
| 25 |
+
}
|
| 26 |
+
return newList;
|
| 27 |
+
}
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
Program outputs:
|
| 31 |
+
List before: [5, 1, 8]
|
| 32 |
+
New list: [6, 2, 9]
|
| 33 |
+
List after: [5, 1, 8]
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
====================================================================
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
Of course, the method can also create an object from scratch, and return it.
|
| 41 |
+
|
| 42 |
+
The example creates a NEW LIST with the number of EMPTY STRINGS specified by the given parameter:
|
| 43 |
+
|
| 44 |
+
import java.util.ArrayList;
|
| 45 |
+
|
| 46 |
+
public class Example {
|
| 47 |
+
public static void main(String[] parameters){
|
| 48 |
+
ArrayList<String> strings = createList(10);
|
| 49 |
+
System.out.println("List size:" + strings.size());
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
public static ArrayList<String> createList(int size) {
|
| 53 |
+
ArrayList<String> list = new ArrayList<>();
|
| 54 |
+
for (int i=0; i<size; i++) {
|
| 55 |
+
list.add("");
|
| 56 |
+
}
|
| 57 |
+
return list;
|
| 58 |
+
}
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
Program outputs:
|
| 62 |
+
List size: 10
|
| 63 |
+
|
| 64 |
+
|