Spaces:
Running
Running
| It is often better practice to CREATE a NEW OBJECT and RETURN it from the method. | |
| In this case, the original object is not changed. | |
| The normal way to return an object is with a return statement. | |
| 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. | |
| import java.util.ArrayList; | |
| public class Example { | |
| public static void main(String[] parameters){ | |
| ArrayList<Integer> numbers = new ArrayList<>(); | |
| numbers.add(5); | |
| numbers.add(1); | |
| numbers.add(8); | |
| System.out.println("List before: " + numbers); | |
| System.out.println("New list: " + increasebyOne(numbers)); | |
| System.out.println("List after: " + numbers); | |
| } | |
| public static ArrayList<Integer> increasebyOne(ArrayList<Integer> numbers) { | |
| ArrayList<Integer> newList = new ArrayList<>(); | |
| for (int element : numbers) { | |
| newList.add(element + 1); | |
| } | |
| return newList; | |
| } | |
| } | |
| Program outputs: | |
| List before: [5, 1, 8] | |
| New list: [6, 2, 9] | |
| List after: [5, 1, 8] | |
| ==================================================================== | |
| Of course, the method can also create an object from scratch, and return it. | |
| The example creates a NEW LIST with the number of EMPTY STRINGS specified by the given parameter: | |
| import java.util.ArrayList; | |
| public class Example { | |
| public static void main(String[] parameters){ | |
| ArrayList<String> strings = createList(10); | |
| System.out.println("List size:" + strings.size()); | |
| } | |
| public static ArrayList<String> createList(int size) { | |
| ArrayList<String> list = new ArrayList<>(); | |
| for (int i=0; i<size; i++) { | |
| list.add(""); | |
| } | |
| return list; | |
| } | |
| } | |
| Program outputs: | |
| List size: 10 | |