Reputation: 21
When do I need to choose one or the other method for lists? What about the resources we use?
List<String> names = new ArrayList<>(something.getList);
List<String> names = something.getList;
Upvotes: 0
Views: 58
Reputation: 1453
This is the preferred way to do things, it means later on you can change the List
of names
to be of a different implementation of List
because List
is the interface and ArrayList
is the comcrete implementation. Later in life you may want to change this to be a LinkedList
or other implementation that uses the List
interface.
I would do like this:
List<String> names = new ArrayList<String>(something.getList());
Upvotes: 0
Reputation: 1329
Doing this List<String> names = something.getList;
assigns another reference to the something.getList
object namely names
. With the other syntax you get a brand new names
object. As for which to use, is it actually a question of what you need, if you need to pass around a list i'd suggest you to use an Immutable List.
Upvotes: 1