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
Related
PMD would report a violation for:
ArrayList<Object> list = new ArrayList<Object>();
The violation was "Avoid using implementation types like 'ArrayList'; use the interface instead".
The following line would correct the violation:
List<Object> list = new ArrayList<Object>();
Why should the latter with List be used instead of ArrayList?
Using interfaces over concrete types is the key for good encapsulation and for loose coupling your code.
It's even a good idea to follow this practice when writing your own APIs. If you do, you'll find later that it's easier to add unit tests to your code (using Mocking techniques), and to change the underlying implementation if needed in the future.
Here's a good article on the subject.
Hope it helps!
This is preferred because you decouple your code from the implementation of the list. Using the interface lets you easily change the implementation, ArrayList in this case, to another list implementation without changing any of the rest of the code as long as it only uses methods defined in List.
In general I agree that decoupling interface from implementation is a good thing and will make your code easier to maintain.
There are, however, exceptions that you must consider. Accessing objects through interfaces adds an additional layer of indirection that will make your code slower.
For interest I ran an experiment that generated ten billion sequential accesses to a 1 million length ArrayList. On my 2.4Ghz MacBook, accessing the ArrayList through a List interface took 2.10 seconds on average, when declaring it of type ArrayList it took on average 1.67 seconds.
If you are working with large lists, deep inside an inner loop or frequently called function, then this is something to consider.
ArrayList and LinkedList are two implementations of a List, which is an ordered collection of items. Logic-wise it doesn't matter if you use an ArrayList or a LinkedList, so you shouldn't constrain the type to be that.
This contrasts with say, Collection and List, which are different things (List implies sorting, Collection does not).
Why should the latter with List be used instead of ArrayList?
It's a good practice : Program to interface rather than implementation
By replacing ArrayList with List, you can change List implementation in future as below depending on your business use case.
List<Object> list = new LinkedList<Object>();
/* Doubly-linked list implementation of the List and Deque interfaces.
Implements all optional list operations, and permits all elements (including null).*/
OR
List<Object> list = new CopyOnWriteArrayList<Object>();
/* A thread-safe variant of ArrayList in which all mutative operations
(add, set, and so on) are implemented by making a fresh copy of the underlying array.*/
OR
List<Object> list = new Stack<Object>();
/* The Stack class represents a last-in-first-out (LIFO) stack of objects.*/
OR
some other List specific implementation.
List interface defines contract and specific implementation of List can be changed. In this way, interface and implementation are loosely coupled.
Related SE question:
What does it mean to "program to an interface"?
Even for local variables, using the interface over the concrete class helps. You may end up calling a method that is outside the interface and then it is difficult to change the implementation of the List if necessary.
Also, it is best to use the least specific class or interface in a declaration. If element order does not matter, use a Collection instead of a List. That gives your code the maximum flexibility.
Properties of your classes/interfaces should be exposed through interfaces because it gives your classes a contract of behavior to use, regardless of the implementation.
However...
In local variable declarations, it makes little sense to do this:
public void someMethod() {
List theList = new ArrayList();
//do stuff with the list
}
If its a local variable, just use the type. It is still implicitly upcastable to its appropriate interface, and your methods should hopefully accept the interface types for its arguments, but for local variables, it makes total sense to use the implementation type as a container, just in case you do need the implementation-specific functionality.
In general for your line of code it does not make sense to bother with interfaces. But, if we are talking about APIs there is a really good reason. I got small class
class Counter {
static int sizeOf(List<?> items) {
return items.size();
}
}
In this case is usage of interface required. Because I want to count size of every possible implementation including my own custom. class MyList extends AbstractList<String>....
Interface is exposed to the end user. One class can implement multiple interface. User who have expose to specific interface have access to some specific behavior which are defined in that particular interface.
One interface also have multiple implementation. Based on the scenario system will work with different scenario (Implementation of the interface).
let me know if you need more explanation.
The interface often has better representation in the debugger view than the concrete class.
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.
Could any one explain,what is the difference between creating reference name using Object or using Interface.
ex1
ArrayList li=new ArrayList();// creating reference using class name
ex2
List li=new ArrayList()//creating reference using interface name
In real scenario why developers using ex2?
What are the advantages for using ex2?
The second approach is programming to an interface. It makes it clear that although you may be dependent on some aspects of the behaviour of the chosen implementation (e.g. its performance characteristics, or its sort order etc) you're only relying on the members declared in the interface. This generally makes it easier to later swap out one implementation with another.
(If you are relying on some very specific aspect of an implementation, I find it's usually a good idea to explicitly say so, to avoid surprises later.)
It means you are coding to a contract and not an implementation. In your example the List contact. If later you need a different type of list all you need to do is change one line where you make your declaration. It makes making changes in the future easier.
If you need specific methods on ArrayList that aren't in list then using ex1 is valid. Although if you change from ArrayList it may be harder. This link may be useful http://jdevelopment.nl/java-best-practices-5-code-to-interface-access-by-name-and-instance-data/
The second has much more advantages:
It is considered good style to store a reference to a HashSet or TreeSet in a variable of type Set. For example:
Set<String> names = new HashSet<String>();
This way, you have to change only one line if you decide to use a TreeSet instead.
Also, methods that operate on sets should specify parameters of type Set:
public static void print(Set<String> s)
Then the method can be used for all set implementations.
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).
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