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?
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.
An ArrayList does not check for duplicates, you could stuff the same object in there over and over again.
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.
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.
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.
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