java Queue interface polymorphism - java

I was reading http://www.docjar.com/html/api/java/util/LinkedList.java.html
When you declare a queue in Java
Queue<Integer> queue = new LinkedList<Integer>();
What happens behind the scene ? because I see queue is an interface with just method signatures, and LinkedList doesn't directly implement it, so how does it override those methods (add(), peek(), poll(), offer(), and remove() ) and do the polymorphism like that ? I mean you can only access some certain methods but not all of them from LinkedList for example public void add(int index, E element) is no longer available as it makes the apparent type to Queue. Also didn't we need to cast it ?

From the source code of the JDK:
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{
So LinkedList<E> doesn't directly implement Queue<E>, but it does implement Deque<E>, which extends Queue<E>:
public interface Deque<E> extends Queue<E> {
Threfore, LinkedList<E> inherits the abstract methods of Queue<E>.
The overriding methods are defined directly in LinkedList<E> - as usual.

because I see queue is an interface with just method signatures, and LinkedList doesn't directly implement it
LinkedList does implement a Queue: http://docs.oracle.com/javase/6/docs/api/java/util/LinkedList.html

Refer this
http://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html

LinkedList does implement Queue. When an object is declared using an interface, the compiler treats it solely as an object of that type. however, since you cannot instantiate an interface, you need to instantiate it as a class that implements that interface. In this case, you will not be able to access some of LinkedList's methods, (push(), pop(), for example), because the compiler identifies queue as a Queue<Integer>. However, since it was instantiated as a LinkedList<Integer>, and can be casted easily to a LinkedList.

Related

Where are the methods of the Iterator Interface actually implemented in the Collections Framework?

Following the hierarchy of the Collections Framework in Java, I struggle to understand where these 2 methods of the Iterator Interface are being implemented.
boolean hasNext();
E next();
The other 2 methods
default void remove()
default void forEachRemaining(Consumer<? super E> action)
have default implementations in the Iterator Interface itself (although they are probably overridden somewhere else too).
image source: https://www.javatpoint.com/collections-in-java
I know that depending on the hierarchy, for example Interface -> Interface -> Class, the implementation can be either in the interface itself as a default method or in the concrete class. But lets take for example the ArrayList, where in the whole hierarchy are the hasNext() and next() methods being implemented.
Collection implements Iterable and Iterable has the method iterator() that returns the Iterator interface, so implementations dont have to implement the Iterator interface.
If you take ArrayList for example, it inherits AbstractList which implements iterator and that is used by different lists implementations.

Defining priority queue

Consider the following declaration of the priority class class PriorityQueue<E extends Comparable<E>> extends Queue<E> { in contrast to the one provided in the Java packages, which has a comparator as an attribute to compare. This instead forces the object for which the priority queue is maintained to have its comparable implementation. Are there any pros and cons of this approach?
My Thoughts:
One thing I can think of is that this will force the priority queue to use the object comparators and won't provide the ability to implement its custom comparator as the user of the class may want to build the queue based on some different comparator.
Consider the following declaration of the priority class class PriorityQueue<E extends Comparable> extends Queue {}
What if you want to put an object in the queue, and this object does not implement the Comparable interface.
There is no need to restrict the placed object must implement the Comparable interface, which is more flexible.
For the same object, the logic of comparison may be inconsistent in different scenarios, so a comparator needs to be passed in from the outside, and the object itself does not need to implement a comparator.
(Above are my personal thoughts)

What is benefit of implementing an interface while the extended class also has implemented it? [duplicate]

When I was seeing the declaration of ArrayList
class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
which implements List interface even though ArrayList's superclass AbstractList implements the same List interface.
abstract class AbstractList<E> extends AbstractCollection<E> implements List<E>
Similar declarations can be found on HashMap, LinkedHashMap declarations also.
In the declaration of LinkedHashMap, it implements Map interface only and not the other interfaces implemented by its superclass HashMap.
So there might be some benefits of having such declarations.
There are no functional benefits to declaring them again, it does not affect the behavior in any way.
I guess it's only added to make it clearer which interfaces are implemented.
This is done for documentation purposes only, to make it immediately clear to the user of the class which interfaces the class implements.
The redundant implements clause makes no difference to the compiler.
Yes. It could've been omitted. But thus it is immediately visible that it is a List. Otherwise an extra click through the code / documentation would be required. I think that's the reason - clarity.
And to add what Joeri Hendrickx commented - it is for the purpose of showing that ArrayList implements List. AbstractList in the whole picture is just for convenience and to reduce code duplication between List implementations.
Reference: Why does ArrayList have "implements List"?
Totally unnecessary. I wouldn't do it at all.
It's unclear why they did that by then. But by now apparently it's a mistake, since everybody is surprised by it when they first notice this odd redundancy.
Well, this way you must implement List<E> methods when you create a subclass to AbstractList, and you can also use an ArrayList as an AbstractList.
ArrayList<T> and AbstractList<T> implement List<T> for different purposes.
List<T> establishes what is required for a class to be a list.
ArrayList<T> implements List<T> as part of defining its own interface. This is essential to what ArrayList<T> is.
ArrayList<T> extends AbstractList<T> as part of its own implementation. This is entirely optional: one could have implemented ArrayList<T> from scratch without inheriting AbstractList<T>, and the class would work in the same way.
AbstractList<T> is intended as a base class for other implementations of List<T>. Instead of establishing an interface, it follows an existing one. AbstractList<T>'s implementation of List<T> is not required, everything would compile and run without it just the same. However, inheriting List<T> lets Java compiler spot potential discrepancies between the interface methods and the methods of AbstractList<T>, so it is a very good idea for AbstractList<T> to implement List<T> interface.

Why does AbstractCollection implement both Iterable and Collection?

AbstractCollection implements both the Iterable and Collection interfaces. However, Collection is a subinterface of Iterable. Would it not suffice just to have AbstractCollection implement Collection?
The Javadocs for AbstractCollection could be interpreted that AbstractCollection directly implements Collection and Iterable.
All Implemented Interfaces:
Iterable, Collection
However, a quick look at the source code indicates that it only directly implements Collection.
public abstract class AbstractCollection<E> implements Collection<E> {
Therefore, the Javadocs must be interpreted as saying that the class implements the given interfaces directly or indirectly. As you've indicated, there would be no need for AbstractCollection to implement Iterable directly, because it already implements Collection. The source code shows that it doesn't implement Iterable directly. It does suffice for AbstractCollection to implement only Collection directly.
Yes. It would suffice. But, explicitly listing both allows one to tell (by simple inspection) that AbstractCollection implements both Iterable and Collection (also, because it's abstract it doesn't necessarily implement either interface - but any concrete sub-class will).

Implementation of Iterator methods

I am working with collections. One thing which is bothering me is: where is the Implementations of the methods of java.util.Iterator Interface? In which class these methods are implemented?
public abstract boolean hasNext();
public abstract E next();
public abstract void remove();
I searched the source code of the java API, but didn't find the implementation of these methods in any class.
Iterator is an interface and it has around 50 implementations in the java api itself.
Since the iterator needs to compy with the iterating object type, for ex if you want to iterate an ArrayList the iterator instance which your iterator() method returns is of new Itr type. see the implementation in java.util.AbstractList class which forms the base class for ArrayList
There are multiple classes in JDK where It has been implemented. ArrayList is very good example for your concern. You can go through the code in openJDK. And the iterator method defination is -
public Iterator<E> iterator() {
return new Itr();
}
Where This Itr private class implements Iterator<E> and define all itarator method.
You can search java apis who implements Iterator. Those classes all have implements the above methods. Go to browse the jdk source code. It will help you a lot.
In case you are using eclipse and you have source code configured in eclipse itself.
Just select the method and press Ctrl + T (show type hierarchy) and you can see all the classes in which the method has been implemented.

Categories