Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice to declare ArrayList or collection implementation classes

Can any one explain what is the difference in the following declaration of ArrayList to store String.

List type1 = new ArrayList();
List type2 = new ArrayList<String>();
List<String> type3 = new ArrayList<String>();
ArrayList<String> type4 = new ArrayList<String>();
List<String> type5 = null;
ArrayList<String> type6 = null;

so which of the above declaration is best practice to declare an ArrayList of String and why?

like image 271
Naveen Avatar asked Apr 19 '15 07:04

Naveen


People also ask

How do you declare an ArrayList in a class?

You can declare the ArrayList within the class, but then add items within the constructor. public class System{ ArrayList<Product> list = new ArrayList<Product>(); public System(){ list. add(param1, param2, param3); //add stuff here. } }

Which is the preferred way to declare a variable of type ArrayList in Java?

The general syntax of this method is:ArrayList<data_type> list_name = new ArrayList<>(); For Example, you can create a generic ArrayList of type String using the following statement. ArrayList<String> arraylist = new ArrayList<>(); This will create an empty ArrayList named 'arraylist' of type String.


1 Answers

The first two use raw types. Doing that means your list isn't type-safe at all. The compiler will let you store Integers inside even if your intention is to have a list of strings. The compiler will emit a warning, that you should not ignore.

The third one is right. It tells the compiler that your intention is to use a List of strings, and that the specific implementation you chose is ArrayList. If you change your mind later and want to use a LinkedList, this line of code is the only one you need to change.

The fourth one tells the compiler that your program doest't just need a List. It needs this List to be an ArrayList. This is OK if your code indeed needs to call methods that are specific to ArrayList, and are not present in the List interface. But in 99.9% of the cases, that's not the case and you should prefer the third one.

The two last ones declare a variable and initialize it to null instead of creating a list. That is a design smell. You'll have to make sure everywhere, before using the list, that it's not null. It's much safer to initialize it with a valid list right away.

like image 140
JB Nizet Avatar answered Oct 19 '22 03:10

JB Nizet