Spaces:
Running
Running
File size: 1,800 Bytes
0e8ae4a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | 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
|