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
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.
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.
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.
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.
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?
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