Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create ArrayList properly? [duplicate]

Below are two ways how to create ArrayList:

List<String/*or other object*/> arrList = new ArrayList();//Imports List, ArrayList
ArrayList<String/*or other object*/> arrList = new ArrayList();//Imports just ArrayList

What is the difference? Which method should be used?

like image 223
Ernestas Gruodis Avatar asked Aug 28 '13 15:08

Ernestas Gruodis


People also ask

How do you duplicate an ArrayList?

The clone() method of the ArrayList class is used to clone an ArrayList to another ArrayList in Java as it returns a shallow copy of its caller ArrayList. Syntax: public Object clone(); Return Value: This function returns a copy of the instance of Object.

Can ArrayList store duplicates?

An ArrayList does not check for duplicates, you could stuff the same object in there over and over again.

Can an ArrayList be double?

Can an ArrayList contain doubles? The Java collection classes, including ArrayList, have one major constraint: they can only store pointers to objects, not primitives. So an ArrayList can store pointers to String objects or Color objects, but an ArrayList cannot store a collection of primitives like int or double.


2 Answers

The first form is recommended for the public interface of a class (say, the declaration of the attributes in a class). It's a well-known advice that you should program for an interface, not for a concrete implementation (this is stated in Design Patterns) - the number of classes you have to import has little to do with the quality of code and good design.

The advantage of the first form is that it'll allow you to easily swap implementations later on, if the need arises - whereas the second implementation sets in stone the implementing class, making your code harder to evolve and less flexible.

There are cases when it's OK to declare and use concrete classes, though (for instance, for a little bump in performance). But the public interface of a class should use interfaces whenever possible, it'll make future changes easier to implement.

like image 176
Óscar López Avatar answered Sep 20 '22 04:09

Óscar López


First ways is called coding to interface

Second one is called coding to implementation.

The advantage with the second one is that it gives you the flexibility to change the implemneatation class later without any code change. For example today you are using ArrayList but if tomorrow you want to change it to LinkedList then simply change the implmentation class in your list definition.

like image 22
Juned Ahsan Avatar answered Sep 21 '22 04:09

Juned Ahsan