Why LinkedList and arraylist extends AbstractList in java? - java

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.

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.

Why we cannot implement collection interface directly by a concrete class?

Collection interface defines the most common general methods which can be applicable for any Collection object.
Some of the methods are like:
1) boolean add(Object obj)
2) boolean addAll(Collection c)
3) boolean remove(Object obj)
4) boolean removeAll(Collection c) (Removes particular group of
objects.)
5) boolean retainAll(Collection c) (Removes all the elements except
those present in c)
I want know the justification for this statement.
There is no concrete class which implements collection interface
directly.
There is nothing stopping you from creating a concrete direct implementation of Collection. However, such an implementation would probably have some additional properties not covered by the Collection contract.
For example, if the elements of your Collection implementation have an ordering, you might as well implement the List interface.
On the other hand, if the storage of your Collection implementation doesn't allow duplicate elements, you might as well implement the Set interface.
...and so on.
This may give you an idea why no concrete direct implementation was deemed necessary by the designers of the standard Collections library.

java Queue interface polymorphism

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.

Where is the iterator interface implementation in Java 5 and above?

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

In java class java.util.Iterator interface has been implemented?

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.

Categories