Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lists.newArrayList vs new ArrayList

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()?

like image 262
asela38 Avatar asked Apr 02 '12 17:04

asela38


People also ask

What is 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).

Which is better list or ArrayList?

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.

What is the difference between a list and an ArrayList?

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.

Why do we use list new ArrayList?

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.


Video Answer


1 Answers

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<>(); 
like image 151
Bozho Avatar answered Oct 12 '22 22:10

Bozho