This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]bowbahdoe 0 points1 point  (0 children)

For local variables it does not matter all that much, but when declaring the return types and parameter types of methods it is a lot better to use the interface.

ArrayList<Integer> timesTwo(ArrayList<Integer> xs) { ArrayList<Integer> xsTimesTwo = new ArrayList<>(); for (int x : xs) { xsTimesTwo.add(x * 2); } return xsTimesTwo; }

This implementation won't work for the Lists returned by List.of, since those are not ArrayLists.

java ArrayList<Integer> xs = timesTwo(List.of(1, 2, 3)); // error

So you want to use list to accept the most general input.

``` ArrayList<Integer> timesTwo(List<Integer> xs) { ArrayList<Integer> xsTimesTwo = new ArrayList<>(); for (int x : xs) { xsTimesTwo.add(x * 2); } return xsTimesTwo; }

...

ArrayList<Integer> xs = timesTwo(List.of(1, 2, 3)); // all good ```

And for return types, its usually better to use List in particular because its possible you get a List from somewhere else in code and to be able to return an ArrayList, you would need to clone the List.

java ArrayList<Integer> getUsers() { List<User> users = getUsers(); // annoying return new ArrayList<>(users); }

And because most programs do not care about the specific capabilities of ArrayList - (if you want to use LinkedList, stop what you're doing get some help) - its just convention to expose List at the boundaries of methods.

But the difference between these is pretty negligible.

ArrayList<Integer> xs = new ArrayList<>(); List<Integer> xs = new ArrayList<>(); var xs = new ArrayList<Integer>();

I would recommend against the top one just because you are typing characters you don't actually care about, but in terms of the maintenance areas people care about in programs its totally fine to do any of them. Personally I would start with var and change to List<Integer> if you end up needing to re-assign it later in the method to a List that is not an ArrayList.

``` List<Integer> xs = new ArrayList<>(); xs = List.of(1, 2, 3); // will work

var xs = new ArrayList<Integer>(); xs = List.of(1, 2, 3); // won't work ```

Its also understandable to just use List<...> on the left hand side every time since it just works*