Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the difference between List<String> stringList = new ArrayList<String>() and List<String> stringList = new ArrayList()?

Tags:

java

arraylist

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?

like image 211
Smrita Avatar asked Apr 05 '14 02:04

Smrita


People also ask

What is the difference between List String and ArrayList String?

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.

What is the difference between List String []> and List String >?

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.

Is ArrayList and List the same?

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.

Why do we do 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.


1 Answers

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.

like image 162
Dawood ibn Kareem Avatar answered Sep 26 '22 13:09

Dawood ibn Kareem