This question already has answers here:
Type List vs type ArrayList in Java [duplicate]
(15 answers)
List versus ArrayList as reference type?
(3 answers)
Closed 9 years ago.
Is there a difference between these two? If so, what is it?
List<Integer> x = new ArrayList<Integer>();
and
ArrayList<Integer> x = new ArrayList<Integer>();
The first declaration lets you program to interface. It ensures that later on you can safely replace ArrayList with, say, LinkedList, and the rest of code is going to compile.
The second declaration lets you program to the class, so you could potentially use methods of ArrayList which do not implement the List interface. For example, you can call ensureCapacity() on the list declared as ArrayList, but not on a list declared as List. Although generally programming to interface should be preferred, there is nothing wrong with doing it if you must call class-specific methods: for example, ability to call ensureCapacity() could save some unnecessary reallocations if you know the new target size of your list.
The former is preferred. It allows changing the implementation without changing code that depends on the field.
In Effective Java, Joshua Bloch says:
If appropriate interface types exist, then parameters, return values, variables and fields should all be declared using interface types.
...
If you get into the habit of using interfaces as types, your program will be much more flexible.
If you code to interfaces then you can change the implementation without much hassle
List<Integer> x = new ArrayList<Integer>();
you can make x now point to a LinkedList or any other implementation of List with only one line of code. If you need a specific method that is in ArrayList then having ArrayList on the left hand side is perfectly acceptable. 99 times out of 100 thought you wont so List is preferred
With ArrayList you can specify an intitalsize and so ArrayList has trimToSize() method to trim its size to the current size.With List<Integer> you won't be able to trim the size unless you cast it back to ArrayList
Related
This question already has answers here:
What is the difference between the HashMap and Map objects in Java?
(13 answers)
Closed 8 years ago.
I am trying to understand what is the difference between the below 2 lines of code.
I know for a reason that one is of the reference type List and the other of the reference type ArrayList. But does it really matter or is it just 2 different ways of doing the same thing ?
Its not only with these classes/interface but with others as well. I believe it is a Polymorphism feature of an object taking different forms is that correct ?
List a1 = new ArrayList();
ArrayList a1 = new ArrayList();
You don't declare objects, you declare variables (and members).
The difference in the interface you have to the object. In the first case, the interface is List, whereas in the second it's ArrayList. The underlying object is the same, but you have different access to it. In theory, ArrayList could have methods that List doesn't have (although in practice I don't think it does).
The advantage to using List is that you can change the underlying object to be a different kind of list (by changing what kind you create) without breaking your contract with any code that's using it. If you declare it as ArrayList, you have to change your contract if you want to change the underlying implementation.
Disclosure: This is an adapted form of my answer to this question. It's basically the same question, but you probably wouldn't find it when looking with the terms you were using. :-)
List a1 is an interface meaning that for example it can reference a LinkedList as well (doesn't restrict the implementation to ArrayList).
While ArrayList a1 can be only assigned ArrayList instances, which is a restriction you don't wish to have sometimes.
It is usually considered better approach to use interfaces (List, Map etc.) instead of concrete types especially if you expose methods to external apps, therefore you don't enforce implementation details. You just expect the variable a1 to behave as a List.
List is an interface, ArrayList implements that interface.
List a1 = new ArrayList();
a1 will be a List variable that contains an instance of the object ArrayList, the cast of the new ArrayList to List will be done implicitly.
It does have to do with inheritance/polymorphism. Think of it as similar to:
Animal dog1 = new Dog();
Dog dog2 = new Dog();
Both will let you perhaps .eat(), but only dog2 can .bark()
This question already has answers here:
Type List vs type ArrayList in Java [duplicate]
(15 answers)
Closed 9 years ago.
I have observed in Java programming language, we code like following:
List mylist = new ArrayList();
Why we should not use following instead of above one?
ArrayList mylist = new ArrayList();
While the second option is viable, the first is preferable in most cases. Typically you want to code to interfaces to make your code less coupled and more cohesive. This is a type of data abstraction, where the user of mylist (I would suggest myList), does not care of the actual implementation of it, only that it is a list.
We may want to change the underlying data structure at some point, and by keeping references, we only need to change the declaration.
The separation of Abstract Data Type and specific implementation is one the key aspects of object oriented programming.
See Interface Instansiation
Just to avoid tight coupling. You should in theory never tie yourself to implementation details, because they might change, opposite to interface contract, which is supposed to be stable. Also, it really simplifies testing.
You could view interface as an overall contract all implementing classes must obey. Instead, implementation-specific details may vary, like how data is represented internally, accessed, etc. - the information that you'd never want to rely on.
If you use ArrayList, you are saying it has to be an ArrayList, not any other kind of List, and to replace it you would have to change every reference to the type. If you use List you are making it clear there is nothing special about the List and it is used as a plain list. It can be changed to another List by changing just one line.
This question already has an answer here:
What is the difference between List and ArrayList? [duplicate]
(1 answer)
Closed 10 years ago.
Is there any Difference between two lines in the following
ArrayList<String> arrName = new ArrayList<String>();
List<String> arrName = new ArrayList<String>();
Thanks for Reply
Almost always the second one is preferred over the first one. The second has the advantage that the implementation of the List can change (to a LinkedList for example), without affecting the rest of the code. This is will be difficult to do with an ArrayList, not only because you will need to change ArrayList to LinkedList everywhere, but also because you may have used ArrayList specific methods.
Try to hide specific implementation behind an Interface whenever possible. see this
The second approach is usually the preferred one as it hides the implementation behind an interface.
This means that later on, if the requirements will change and will require another implementation of the List interface, you can change just one line of code and everything else will still work because you were coding to an interface not to a class.
There is not much difference per se, but List shall be used whenever possible as it is an interface and you may see in standard libraries' methods parameters are generally List<K>, so that any specific implementation can be passed, like ArrayList or LinkedList.
Second is example of Program to Interface and its the preferred way.
For details What does it mean to "program to an interface"?
The latter is usually recommended as long as you only need a List interface later on. That's called "programming to interface, not implementation".
As for the detailed difference between them, I have answered in another question on stackoverflow: The difference between "C c = new C()" and "A c = new C()" when C is a subclass of A in Java
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why should the interface for a Java class be prefered?
I m relatively new to java and i have just started on collections framework.
While on ArrayList I encountered on two ways people declare it. For example to declare an ArrayList of Strings :
List<String> l = new ArrayList<String>();
or
ArrayList<String> al = new ArrayList<String>();
Which one of these two should I use and what is the difference between them?
I know that the actual methods called are decided at runtime and hence the methods called will all be of ArrayList class only but still the first declaration restricts the methods that can be called.
The first way is, I have heard, called "coding to an interface". Any method will be invoked using the variable l and hence only methods provided by List interface can be called, whereas, in the second example we can call all the methods provided not only by List but by the Object class also (like finalize(), wait() etc). So why even in the first place people even use the first declaration??
You should always use least specific interface possible. This makes it easier to substitute alternate implementations if a more appropriate one exists. For example, methods that take List don't care if the list is a linked list or an array list. You can choose whichever one is more appropriate.
I personally recommend using List<String> l = new ArrayList<String>();
The reason is you typically don't need to know you're working with an ArrayList. You just need something that operates like a list. There's a lot of behaviors on ArrayList that people don't need access to. Consider "EnsureCapacity". They don't need that - they just need the List operations. As a general rule, you want to limit the exposure of data and functionality on a "need to know" basis, and users of your list do not need to know (by default) what implementation you used.
Obviously, if they do need to know that you're using an ArrayList instead of a LinkedList, for instance, then you would want to use an ArrayList reference instead of a List reference. For most purposes though, that's not necessary.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Type List vs type ArrayList in Java
Why is it recommended to do this:
List<String> myArrayList = new ArrayList<String>
or same with Map interface and HashMap class
rather than:
ArrayList<String> myArrayList = new ArrayList<String>
Because the consuming code of the myArrayList variable won't be tied to a particular implementation of this interface.
With the first (preferred) line you say, that your code needs a List, with the second line you say your code needs an ArrayList. Usually, you path variable instances around. If you now change the myArrayList instance for some reason you would have to change too much code.
You should not use:
List<String> myArrayList = new ArrayList<String>
Why you should use the type List instead of ArrayList (unless you really need feature of the ArrayList that is missing in the List interface) is already explained in the other answer.
But I think it is even more important to use proper names. So if you use List as type for the variable, the name should not tell that it is an ArrayList. It would be even better if the name indicated the use of the variable.
Yes, this is picky. But using good names will make it a lot easier to understand the code in a year from now and for colleagues.