This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Why should the interface for a Java class be prefered?
ArrayList<Integer> al = new ArrayList<Integer>();
List<Integer> l = new ArrayList<Integer>();
what is the difference between these 2 lines? Is there any rules that I should use former one rather than later one in any case? Or vise versa? What is advantage or disadvantage of using particular one?
Thanks.
The first line creates an ArrayList and stores it in a variable of type of ArrayList, the second line stores it in a variable of type List.
List is an interface of which ArrayList is an implementation. The rule of thumb for deciding which type to store the instance in (List or a specific implementation, like ArrayList) is that you should store at the most generalized level suitable for your needs. This means that if you know that the variable must conform to behavior only exhibited by ArrayList and not a List in general, then you should use ArrayList, otherwise, use List. (This holds for LinkedList or other List implementations, too)
The reason why you want to use the second line it's because it's usually better to program to interfaces than to classes, sometimes it's related to good practices to do that and one of the benefits it's that you end up with code that:
It's better to test
Can use different implementations
It's not coupled to ArrayList
For more information you can take a look at the "Hollywood principle" or the Strategy pattern
Related
This question already has answers here:
What does it mean to "program to an interface"?
(33 answers)
Closed 5 years ago.
I was a bit confused, when we use
List<String> lst = new LinkedList<>();
when we use
LinkedList<String> lklst = new LinkedList<>();
At the beginning, I thought they are the same, but today, I realized they are not the same. For example, if I call lst.getFirst() It will tell me there is a error. However, if i do lklst.getFirst(), it works fine. My question is when do we use lklst then? why they are different? Also, does it apply same rule for Map. THanks!
On the left hand side you're declaring the type of the variable, lst. Since lst's type is List you can only access methods of a List, even if the object lst points to is really a LinkedList. There's an inherent tradeoff between declaring a variable of a concrete type like LinkedList (access to more methods / behavior) vs. a more abstract interface (safer, better compartmentalized code).
This is a big topic, and there isn't one simple answer for when to do one vs. the other (though there's lots of advice out there about it!) - you'll need to figure out which is appropriate for your use case.
Effective Java - Item 52: Refer to objects by their interfaces is a pretty canonical citation for this issue, and as the title implies suggest preferring List rather than LinkedList.
This question already has answers here:
"Program to an interface". What does it mean? [duplicate]
(8 answers)
Closed 5 years ago.
I was reading this PowerPoint presentation when I came across this:
When you call a method through one of these references, the correct version will be called based on the actual instance of the interface being referred to. This is one of the key features of interfaces. The method to be executed is looked up dynamically at run time, allowing classes to be created later than the code which calls methods on them.
Can anyone explain me about this concept? I referred few websites and book and I am still not clear about how this concept works. From above line it is known that it calls correct version of method. How does it work and when should I cast an object to interface type.
Let's give an example using the List interface. Two of its implementations are ArrayList and LinkedList. The first one is really fast at retrieving a random element (for example the 6th using get(5) method) but is slow at adding and removing elements. The second one is the opposite. Fast at adding and removing but slow at accessing random elements.
Now lets assume that you have a class that has methods that retrieve information about a car dealership. One method retrieves a list of all available car manufacturers while the other method retrieves all the cars the dealership has. In the first case you would want to use an ArrayList because you don't expect the list of manufacturers to change that much, whereas in the second case you want a LinkedList because you expect to sell and buy lots of cars thus making many changes.
However, the one who uses those methods, doesn't really care whether he handles an ArrayList or a LinkedList. All he wants to do is use get(x) and add(Car) or remove(Car) which are all methods of the List interface. Thus, your methods should all have List as their return type and they will decide what implementation they will provide, since it doesn't matter to the one calling them.
This also gives you the advantage of being able to, in the future, change the second method for example from providing a LinkedList into an ArrayList if you decide that you need fast retrieval instead of fast adding and removing. If the method was explicitly returning LinkedList you would have to go and change all the places that it was being called into the new type. But if it was returning simply the interface then no outside change is required!
This question already has answers here:
Why should the interface for a Java class be preferred?
(10 answers)
Closed 8 years ago.
everyone!
Just started studying Java and can not understand one moment, for example:
Set<Integer> intset = new HashSet<Integer>(); (1)
HashSet<Integer> intset2 = new HashSet<Integer>(); (2)
What is the difference between these examples? Or they are the same? (1) example looks like up-casting, so it means that we have HashSet with only Set(interface) methods? Thank you for your reply!
When you write
Set intset = new HashSet();
You give the guarantee that the following code, if not casting, won't use any of the specificities of the HashSet class. This means future implementations may replace HashSet with any other implementation of Set, or maybe receive it from elsewhere. This is actually a best practice as it means your code is less coupled.
Set is an interface and HashSet is an hash implementation of Set interface.
The inset is a Set, so, it can refer any implementation of a Set, like HashSet. On other hand, inset2 can only refer an HashSet object.
This is polymorphism.
What is the difference between these examples?
Example one creates a "pointer" to the space in memory of a type of a Set. That means that you will have ability to manipulate that space in memory using all methods declared in the Set interface.
Example two creates a "pointer" to the space in memory of a type of a HashSet. That means that you will have ability to manipulate that space in memory using all methods declared in the HashSet class.
Or they are the same?
It depends on what you are going to do after those two lines. Set is a common contract for the Set-like collections but sometimes we need more specific methods. That is when you need to downcast you Object to a more specific type. Interfaces are supposed to deal with the commonality.
(1) example looks like upcasting, so it means that we have HashSet with only Set(interface) methods?
Yes.
Set[Set][1] is an interface, HashSet[HashSet][2] is a class, Implementing Set interface methods in HashSet classes, HashSet class implements Set interface
This question already has answers here:
Type List vs type ArrayList in Java [duplicate]
(15 answers)
Closed 10 years ago.
I use this two statements to ArrayList definition:
ArrayList<String> my = new ArrayList<>();
List<String> my2 = new ArrayList<>();
Which one should i use?
With your second definition, you could later replace ArrayList constructor for another type of List, like a LinkedList or a high-performant list, or any other kind of list that may exist in the future. In your first definition, you are tied to the ArrayList implementation forever. You cannot change it, because the rest of your code is trusting in this reference being explicitly an ArrayList.
By using an interface, on the contrary, your code relies on a contract, that of the interface, and not in a particular implementation (like ArrayList). That gives you the power of changing implementations without affecting its users. And change is something that we must foster and plan ahead, simply because we cannot prevent things from changing.
The latter. Program to an interface, not to an implementation.
Depends on what you need. It's generally advised to use interfaces (hence List) if possible, otherwise you're sticked to implementation class. Say, you use ArrayList as input parameter of some method. For some reason (e.g. performance) you decide at some point to switch from ArrayList to LinkedList. So you must change also the type of the input parameter. If you use interface (List), you're more free to switch implementation without the need of refactoring code.
This question already has answers here:
Type List vs type ArrayList in Java [duplicate]
(15 answers)
Closed 10 years ago.
What are the fundamental differences between the two objects? Is one more efficient? Does one have more methods?
List is in interface while ArrayList is a class.
See ArrayList, and List.
E.g, you can't use this setup:
List<String> list = new List<String>();... Because it's an interface.
However, this works:
ArrayList<String> arrayList = new ArrayList<String>();
Also... You can do as duffymo says below, which is more or less the same as implementing the List interface (making your own list implementation).
Consider a line like the following:
List<String> names = new ArrayList<String>();
If you're new to object-oriented architectures, you might have expected instead to see something like ArrayList<String> names = new ArrayList<String>();. After all, you've just said that it's a new ArrayList, so shouldn't you store it in a variable of type ArrayList?
Well, you certainly can do that. However, List is an interface--like a template of sorts--that ArrayList is said to inherit. It is a contract that says "anytime you use a List implementation, you can expect these methods to be available". In the case of List, the methods are things like add, get, etc.
But ArrayList is only one implementation of List. There are others, such as LinkedList. The two have the same interface, and can be used the same way, but work very differently behind the scenes. Where ArrayList is "random" access, meaning that it directly finds a specific element of the array without iterating through the whole list, LinkedList does have to start from the first element and go one-by-one until it gets to the element you need.
The thing is, while you do need to specify which you want when you create the object, you generally only need to communicate no more than the fact that it is a List, so you simply say that's what it is. List communicates that you have a collection that is intended to be in the order that it is given. If you don't need to communicate that much, you might consider passing it around as a Collection, which is another interface (a super-interface of List). Or, if all you need to communicate is that you can iterate over it, you might even call it an Iterable.
List is an interface; ArrayList is a class that implements the List interface.
Interfaces define the method signatures that are required, but say nothing about how they are implemented.
Classes that implement an interface promise to provide public implementations of methods with the identical signatures declared by the interface.
A List defines the interface that ArrayList uses, that allows it to implement methods that will allow all other classes that implement List to be used together or in a similar way. An ArrayList is always also a List, but an List isn't necessarily an ArrayList.
That is, ArrayList implements List (among a few other interfaces).
How to use List and ArrayList, or other implementation of List, is Polymorphism and Inheritance, and also the reason why for using languages such as Java.
In simplicity, Polymorphism is many forms while Inheritance is reuse.
There can be many kinds of concrete and ready to us List that is available to you, such as ArrayList, Vector, LinkedList and Stack. The decision to use which comes from you, and if you look at the List API, you would notice that all of these List implementations extend in one way or another from List.
According to the java docs, List is just an interface, and ArrayList is one of the classes that implement it. There is no inherent efficiency advantage to using ArralyList specifically instead of List-typed references to an ArrayList object.
However, when it comes to "efficiency", there can be a difference between different implementations of the List interface. For instance there can be a small efficiency difference between a LinkedList and an ArrayList, depending on how you're using them.
To quote the java docs on the ArrayList page,
The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation.
In other words, the performance difference will probably be negligible, but you may see some advantage from using an ArrayList (as opposed to a LinkedList).
In case you're interested, ArrayList is implemented with an array that is resized from time to time (most likely whenever your collection doubles in size), which is quite different from the implementation of a LinkedList (see wikipedia for details).