Difference between usage of Interfaces and implementation classes in Java [duplicate] - java

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.

Related

Differnce between interface refrence and concrete class reference [duplicate]

This question already has answers here:
Use interface or type for variable definition in java?
(8 answers)
Closed 8 years ago.
I want to ask a question about using List in Collections API of java :
List <Integer> list = new ArrayList<>();
ArrayList<Integer> aList = new ArrayList<>();
We can use either for making an object of ArrayList, so which is the better way to create an ArrayList, and why?
The first option makes the rest of your code more modular, since you can replace the List implementation used by your code by changing a single line of code.
You'd just have to change
List <Integer> list = new ArrayList<>();
to
List <Integer> list = new SomeOtherListImplementation<>();
Declaring the variable to be ArrayList ties your code to the ArrayList implementation of the List interface.
If, however, your code requires usage of methods of ArrayList that are not part of the List interface, you might have to use an ArrayList variable.
The first case called as programming to interfaces.
If you stick to interface programming and implement your programm later you may change it to some other implementation.
For ex
List <Integer> list = new LinkedList<>();
If you code in first way, when ever you need to change just change the Right Hand Side of the initialization part and you are done without any code breakage and without any compiler error.
ArrayList<Integer> aList = new ArrayList<>();
Above line of code is ok if the variable aList is not modified later.
List <Integer> list = new ArrayList<>();
But if you want to add more flexibility to your code I would suggest this way because you can later declare the list variable to a different List implementation.
List <Integer> list = new LinkedList<>();
It will not break the code because it ensures that you only call the methods that are defined by the List interface.
First approach is modular. Which is taking advantage of fact that "Base class pointer can point to Derived class Object".
This is particularly helpful while we are passing argument. say,
public void display(List<String> names);
LinkedList<String> names = new LinkedList<String>();
display(names);

Trying to understand different ways of declaring an object in Java? [duplicate]

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()

Difference of List and ArrayList in declaration? [duplicate]

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

Assigning ArrayList to List [duplicate]

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

How to declare an ArrayList? [duplicate]

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.

Categories

Resources