Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the List or ArrayList declaration differences in Java?

I am new to Java. I want to know the difference between:

List< String > list = new ArrayList<>();

and

ArrayList< String > list = new ArrayList<String>();

and

ArrayList< String > list = new ArrayList<>();

Thanks

like image 814
Hossein Avatar asked Jan 15 '12 13:01

Hossein


People also ask

What is the difference between an array ArrayList and a List?

An array is a fixed-length data structure. ArrayList is a variable-length data structure. It can be resized itself when needed. It is mandatory to provide the size of an array while initializing it directly or indirectly.

What are 3 differences between an array and an ArrayList in Java?

Array is a fixed length data structure whereas ArrayList is a variable length Collection class. We cannot change length of array once created in Java but ArrayList can be changed. We cannot store primitives in ArrayList, it can only store objects. But array can contain both primitives and objects in Java.

Why do we declare List instead of ArrayList?

By declaring the listStrings variable to be of type List instead of ArrayList, your code is saying that it is more concerned with the contract of behavior as defined by the List interface rather than the implementation of that behavior as provided by the ArrayList class.

What is an ArrayList different types of array?

ArrayList class Java is basically a resizable array i.e. it can grow and shrink in size dynamically according to the values that we add to it. It is present in java. util package. Syntax: To create an ArrayList of Integer type is mentioned below.


1 Answers

The first one is only valid since Java 7, and is the equivalent of

List<String> list = new ArrayList<String>();

It's just less verbose.

Same for the third one, which is equivalent to

ArrayList<String> list = new ArrayList<String>();

and thus strictly equivalent to the second one.

You should prefer the first one, for the reasons mentioned in the answers to the following question: List versus ArrayList as reference type?

like image 159
JB Nizet Avatar answered Nov 15 '22 14:11

JB Nizet