From a functional point of view, both methods do exactly the same: they add "n8"
to the list passed as an argument.
The only difference is in the return
statement: the first method does not return anything, while the second one returns a reference to the same list that was passed as an argument. While all this seems quite obvious, using the second option would allow you to do the following:
ArrayList<String> list = new ArrayList<>();
boolean hasNote = Notes.addEight(list).contains("n8"); // true
Whether this is useful to you or not, it will depend on your specific problem.
In general, it doesn't make sense to have more than one reference pointing to the same object. Consider the following:
ArrayList<String> list1 = new ArrayList<>();
ArrayList<String> list2 = Notes.addEight(list1);
System.out.println("list1 == list2 ? " + (list1 == list2)); // true, they point to
// the same list
System.out.println("list1.equals(list2) ? " + (list1.equals(list2))); // true, since they
// not only contain
// the same
// elements, but
// also point to the
// same list
In this scenario, it doesn't seem to be very useful to have two references pointing to the same list, since it would be as doing this:
ArrayList<String> list1 = new ArrayList<>();
ArrayList<String> list2 = Notes.addEight(list1);
ArrayList<String> list3 = list1;
System.out.println("list1 == list2 ? " + (list1 == list2)); // true
System.out.println("list1.equals(list2) ? " + (list1.equals(list2))); // true
System.out.println("list1 == list3 ? " + (list1 == list3)); // true
System.out.println("list1.equals(list3) ? " + (list1.equals(list2))); // true
Now, it would be different if your Notes.addEight()
method was implemented this way:
public static ArrayList<String> addEight(ArrayList<String> list) {
list.add("n8");
return new ArrayList<>(list); // NOTE THIS! A new ArrayList is being returned
}
If we invoked this new addEight()
method, then things would be different:
ArrayList<String> list1 = new ArrayList<>();
ArrayList<String> list2 = Test.addEight(list1);
ArrayList<String> list3 = list1;
System.out.println("list1 == list2 ? " + (list1 == list2)); // false
System.out.println("list1.equals(list2) ? " + (list1.equals(list2))); // true
System.out.println("list1 == list3 ? " + (list1 == list3)); // true
System.out.println("list1.equals(list3) ? " + (list1.equals(list3))); true
As you see, now list1
and list2
are references that point to different objects (list1 == list2
is false
), while list1.equals(list2)
is true
, since both lists contain the same elements in the same order (they are semantically equal).
However, list1 == list3
is true
, since they actually point to the same list, due to the way list3
was declared (list3
was assigned to list1
by means of the assignment operator =
).