I have been asked in an interview that in which java class iterator interface has been implemented where the hasNext(), next() and remove() methods are defined.
Please let me know. This seems critical.
The iterator interface is implemented in java.util.AbstractList, http://docs.oracle.com/javase/1.5.0/docs/api/java/util/AbstractList.html. Here is an explanation from the documentation: "Unlike the other abstract collection implementations, the programmer does not have to provide an iterator implementation; the iterator and list iterator are implemented by this class, on top the "random access" methods: get(int index), set(int index, Object element), set(int index, Object element), add(int index, Object element) and remove(int index)."
The method iterator() returns an iterator over the elements in the list. You will also see this method on classes that extend the AbstractList: Vector, ArrayList.
java.util.AbstractList is the abstract class providing implementation for the Iterable interface (by implementing List Interface where List extends Collection Ifc; Collection extends Iterable Ifc).
AbstractList has inner class private class Itr which implements Iterator Interface, Means providing implementation for hasNext(), next() methods here.
So iterator() :: AbstractList method is providing new Itr() object for traverse on that collection.
ArrayList, Vector all are sub classes of AbstractList which inherently have access for iterator()::AbstractList API and returning new Iterator object.
Simalarly for Set; AbstractCollection is abstract class for iterator implementation.
We do have one more inner class in java.util.AbstractList i.e
class ListItr extends Itr implements ListIterator
This will allow us to traverse the collection in both direction.
Related
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.
Why LinkedList and ArrayList extends AbstractList in Java?
Abstract classes are used when we want to specify a common behaviour in implementation classes.
But all the methods which are in AbstractList are overridden by ArrayList and LinkedList.
So what is the use of extending this class?
subList(int,int) method is not overriden by both ArrayList and LinkedList, and for this AbstractList provides a common implementation
From Java source
public List<E> subList(int fromIndex, int toIndex) {
return (this instanceof RandomAccess ?
new RandomAccessSubList<E>(this, fromIndex, toIndex) :
new SubList<E>(this, fromIndex, toIndex));
}
In addition there are other methods which are not overriden like toString() and iterator()
You can get Answer from Here,,, AbstractList
This class provides a skeletal implementation of the List interface to minimize the effort required to implement this interface backed by a "random access" data store (such as an array). For sequential access data (such as a linked list), AbstractSequentialList should be used in preference to this Class.
To implement an unmodifiable List, the programmer needs only to extend this class and provide implementations for the get(int index) and size() methods.
To implement a modifiable List, the programmer must additionally override the set(int index, Object element) method (which otherwise throws an UnsupportedOperationException. If the List is variable-size the programmer must additionally override the add(int index, Object element) and remove(int index) methods.
The programmer should generally provide a void (no argument) and Collection constructor, as per the recommendation in the Collection interface specification.
Unlike the other abstract Collection implementations, the programmer does not have to provide an Iterator implementation; the iterator and listIterator are implemented by this class, on top the "random access" methods: get(int index), set(int index, Object element), set(int index, Object element), add(int index, Object element) and remove(int index).
The documentation for each non-abstract methods in this class describes its implementation in detail. Each of these methods may be overridden if the Collection being implemented admits a more efficient implementation.
Not all methods from AbstractList are overridden. Remember that AbstractList subclasses AbstractCollection, which defines methods like containsAll or toString which are not overridden by either ArrayList nor LinkedList.
Usage is noted at the top of the AbstractList source file
"This class provides a skeletal implementation of the {#link List}
interface to minimize the effort required to implement this interface
backed by a "random access" data store (such as an array). For sequential
access data (such as a linked list), {#link AbstractSequentialList} should
be used in preference to this class."
So essentially it provides some methods to build around and a framework that is more robust than the List interface.
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.
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.
As Iterator is an interface with hasNext(), next() and remove() methods. But where is the implementation for all these methods in Java classes?
Almost every concrete collection has its own implementation, optimized for that specific collection. You don't have to bother about the details. But here are some examples:
LinkedList - class ListItr implements ListIterator<E>
ArrayList - class ListItr extends Itr implements ListIterator<E>
HashSet - actually backed by HashMap.keySet()
Becasue Iterator is an interface, you can do fancy things with it, like wrapping and decorating it, without paying attention to the actual implementation.
The Iterator interface is implemented as a inner and private (should be but not necessarily) class in the class/interface that implements the java.lang.Iterable<T> interface. The method of Iterable<T> - Iterator<T> iterator() allows an object to be the target of the "foreach" statement.
For more information read the blog of #Andreas Grech : Java's Iterators and Iterables