What is the best construction for creating a List
of Strings? Is it Lists.newArrayList()
(from guava) or new ArrayList()
?
is it just a personal preference?
or is it just Type generic type inference?
or is there any theoretical or practical value in using Lists.newArrayList()?
Returns a view of the specified string as an immutable list of Character values. static <E> ArrayList<E> newArrayList() Creates a mutable, empty ArrayList instance (for Java 6 and earlier).
ArrayList class is used to create a dynamic array that contains objects. List interface creates a collection of elements that are stored in a sequence and they are identified and accessed using the index. ArrayList creates an array of objects where the array can grow dynamically.
The List is an interface, and the ArrayList is a class of Java Collection framework. The List creates a static array, and the ArrayList creates a dynamic array for storing the objects. So the List can not be expanded once it is created but using the ArrayList, we can expand the array when needed.
List list = new ArrayList(); the rest of your code only knows that data is of type List, which is preferable because it allows you to switch between different implementations of the List interface with ease.
The guava builder saves typing the type arguments multiple times. Compare:
List<Foo<Bar, Baz>> list = Lists.newArrayList(); List<Foo<Bar, Baz>> list = new ArrayList<Foo<Bar, Baz>>();
In Java 7 it's a bit obsolete though, because you have the diamond operator:
List<Foo<Bar, Baz>> list = new ArrayList<>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With