I know that both of the following declaration and initialization are possible in java .
List<String> stringList = new ArrayList<String>()
List<String> stringList = new ArrayList()?
But what exactly are the differences between them?
Also how do you prefer to name the list variables? As in do you prefer to name them variableList or just variables? Or do you have any other approach?
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.
There's really no difference, although the second one will give you a compile warning. They compile to the same bytecode, because the compiler throws away the information about what type parameters you've used.
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.
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.
There's really no difference, although the second one will give you a compile warning.
They compile to the same bytecode, because the compiler throws away the information about what type parameters you've used.
The problem is that the ArrayList
class was invented before generics were, so we used to always have to create it as new ArrayList()
, without specifying the type parameter. Now with generics, we can specify what type of objects will be stored in an ArrayList
and have the compiler check that we use it correctly. The notation for doing that is what you've used in the first example.
But any checking that the compiler does subsequently is based on the type of the variable, not the class of what you've created, so the difference will have no effect at all, past the initial compiler warning.
From Java 7 onwards, the preferred way of writing this is List<String> stringList = new ArrayList<>();
but this notation is unavailable in earlier versions of Java.
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