The Wayback Machine - https://web.archive.org/web/20240930211613/https://www.geeksforgeeks.org/abstractlist-in-java-with-examples/
Open In App

AbstractList in Java with Examples

Last Updated : 04 Apr, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The AbstractList class in Java is a part of the Java Collection Framework and implements the Collection interface and the AbstractCollection class. 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, for which one needs to only extend this AbstractList Class and implement the get(int) and the size() methods. To implement a modifiable list, for which one additionally override the set​(int index, E element) method (which otherwise throws an UnsupportedOperationException). If the list is variable-size, for which one should override the add(int, E) and remove(int) methods.

Class Hierarchy: 

AbstractList-in-Java

Declaration: 

public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E>

where E is the type of elements maintained by this collection.

Constructor: protected AbstractList() – The default constructor, but being protected, it doesn’t allow to create an AbstractList object.

AbstractList<E> al = new ArrayList<E>();

Example 1: AbstractList is an abstract class, so it should be assigned an instance of its subclasses such as ArrayList, LinkedList, or Vector. 

Java




// Java code to illustrate AbstractList
import java.util.*;
 
public class AbstractListDemo {
    public static void main(String args[])
    {
 
        // Creating an empty AbstractList
        AbstractList<String> list = new ArrayList<String>();
 
        // Use add() method to add elements in the list
        list.add("Geeks");
        list.add("for");
        list.add("Geeks");
        list.add("10");
        list.add("20");
 
        // Displaying the AbstractList
        System.out.println("AbstractList:" + list);
    }
}


Output

AbstractList:[Geeks, for, Geeks, 10, 20]

Example 2:

Java




// Java code to illustrate
// methods of AbstractCollection
 
import java.util.*;
 
public class AbstractListDemo {
    public static void main(String args[])
    {
 
        // Creating an empty AbstractList
        AbstractList<String>
            list = new LinkedList<String>();
 
        // Using add() method to add elements in the list
        list.add("Geeks");
        list.add("for");
        list.add("Geeks");
        list.add("10");
        list.add("20");
 
        // Output the list
        System.out.println("AbstractList: " + list);
 
        // Remove the head using remove()
        list.remove(3);
 
        // Print the final list
        System.out.println("Final AbstractList: " + list);
 
        // getting the index of last occurrence
        // using lastIndexOf() method
        int lastindex = list.lastIndexOf("A");
 
        // printing the Index
        System.out.println("Last index of A : "
                        + lastindex);
    }
}


Output

AbstractList: [Geeks, for, Geeks, 10, 20]
Final AbstractList: [Geeks, for, Geeks, 20]
Last index of A : -1

Methods in AbstractList

METHOD

DESCRIPTION

add​(int index, E element) Inserts the specified element at the specified position in this list (optional operation).
add​(E e) Appends the specified element to the end of this list (optional operation).

addAll​(int index, 

Collection<? extends E> c)

Inserts all of the elements in the specified collection into this list at the specified position (optional operation).
clear() Removes all of the elements from this list (optional operation).
 equals​(Object o) Compares the specified object with this list for equality.
get​(int index) Returns the element at the specified position in this list.
hashCode() Returns the hash code value for this list.
indexOf​(Object o) Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.
 iterator() Returns an iterator over the elements in this list in proper sequence.
lastIndexOf​(Object o) Returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element.
listIterator() Returns a list iterator over the elements in this list (in proper sequence).
listIterator​(int index) Returns a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list.
remove​(int index) Removes the element at the specified position in this list (optional operation).
 removeRange​(int fromIndex, int toIndex) Removes from this list all of the elements whose index is between fromIndex, inclusive, and toIndex, exclusive.
 set​(int index, E element) Replaces the element at the specified position in this list with the specified element (optional operation).
 subList​(int fromIndex, int toIndex) Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.

Methods declared in class java.util.AbstractCollection

METHOD

DESCRIPTION

addAll​(Collection<? extends E> c) Adds all of the elements in the specified collection to this collection (optional operation).
contains​(Object o) Returns true if this collection contains the specified element.
 containsAll​(Collection<?> c) Returns true if this collection contains all of the elements in the specified collection.
 isEmpty() Returns true if this collection contains no elements.
 remove​(Object o) Removes a single instance of the specified element from this collection, if it is present (optional operation).
removeAll​(Collection<?> c) Removes all of this collection’s elements that are also contained in the specified collection (optional operation).
 retainAll​(Collection<?> c) Retains only the elements in this collection that are contained in the specified collection (optional operation).
 toArray() Returns an array containing all of the elements in this collection.
toArray​(T[] a) Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array.
 toString() Returns a string representation of this collection.

Methods declared in interface java.util.Collection

METHOD

DESCRIPTION

parallelStream() Returns a possibly parallel Stream with this collection as its source.
removeIf​(Predicate<? super E> filter) Removes all of the elements of this collection that satisfy the given predicate.
stream() Returns a sequential Stream with this collection as its source.
toArray​(IntFunction<T[]> generator)

Returns an array containing all of the elements in this collection, using the

 provided generator function to allocate the returned array.

Methods declared in interface java.util.List                        

METHOD

DESCRIPTION

 addAll​(Collection<? extends E> c)

Appends all of the elements in the specified collection to the end of this list, in the order that

 they are returned by the specified collection’s iterator (optional operation).

 contains​(Object o) Returns true if this list contains the specified element.
 containsAll​(Collection<?> c) Returns true if this list contains all of the elements of the specified collection.
isEmpty() Returns true if this list contains no elements.
remove​(int index) Removes the element at the specified position in this list (optional operation).
removeAll​(Collection<?> c) Removes from this list all of its elements that are contained in the specified collection (optional operation).
 replaceAll​(UnaryOperator<E> operator) Replaces each element of this list with the result of applying the operator to that element.
retainAll​(Collection<?> c) Retains only the elements in this list that are contained in the specified collection (optional operation).
 size() Returns the number of elements in this list.
 sort​(Comparator<? super E> c) Sorts this list according to the order induced by the specified Comparator.
spliterator() Creates a Spliterator over the elements in this list.
 toArray() Returns an array containing all of the elements in this list in proper sequence (from first to last element).
 toArray​(T[] a)

Returns an array containing all of the elements in this list in proper sequence (from first to last element)

; the runtime type of the returned array is that of the specified array.

The AbstractList class in Java is an abstract class that provides a skeletal implementation of the List interface. It is part of the Java Collections Framework and is intended to be subclassed by concrete list implementations like ArrayList and LinkedList.

Here is an example of how you can use the AbstractList class in Java:

Java




import java.util.AbstractList;
import java.util.List;
 
public class MyList extends AbstractList<Integer> {
    private int size;
 
    public MyList(int size) {
        this.size = size;
    }
 
    @Override
    public Integer get(int index) {
        return index;
    }
 
    @Override
    public int size() {
        return size;
    }
 
    public static void main(String[] args) {
        List<Integer> list = new MyList(5);
        for (int i : list) {
            System.out.println(i);
        }
    }
}


Output

0
1
2
3
4

By extending the AbstractList class, you only need to implement the get and size methods, which provides a basic implementation of a list. This can save you a lot of time and code compared to implementing the List interface from scratch.

Advantages of using AbstractList in Java:

  1. Reduced code duplication: By using the AbstractList class as a base, you can reduce the amount of code that you need to write to implement a list, since many of the common methods have already been implemented for you.
  2. Consistent behavior: Since the AbstractList class implements many of the methods in the List interface, you can be sure that your implementation will have consistent behavior with other list implementations, like ArrayList and LinkedList.

Disadvantages of using AbstractList in Java:

  1. Limited functionality: Since the AbstractList class is an abstract class, it provides only a basic implementation of a list. You may need to implement additional methods to provide the full functionality required by your application.
  2. Increased complexity: By extending the AbstractList class, you are increasing the complexity of your code, since you are relying on the base class to provide some of the behavior.

Reference Book: 

A good reference book for learning about the Java Collections Framework and AbstractList is “Java Collections” by Naftalin and Wadler. This book provides a comprehensive look at the Java collections framework, including AbstractList, and includes many examples and exercises to help you understand how to use these classes effectively.

Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/AbstractList.html



Similar Reads

AbstractList addAll() method in Java with Examples
The addAll() method of java.util.AbstractList class is used to insert all of the elements in the specified collection into this list at the specified position. This shifts the element currently at that position (if any) and any subsequent elements to the right (increases their indices). The new elements will appear in this list in the order that th
4 min read
AbstractList clear() method in Java with Examples
The clear() method of java.util.AbstractList class is used to remove all of the elements from this list. The list will be empty after this call returns. Syntax: public void clear() Returns Value: This method does not return anything. Below are the examples to illustrate the clear() method. Example 1: // Java program to demonstrate // clear() method
2 min read
AbstractList equals() method in Java with Examples
The equals() method of java.util.AbstractList class is used to compare the specified object with this list for equality. Returns true if and only if the specified object is also a list, both lists have the same size, and all corresponding pairs of elements in the two lists are equal. (Two elements e1 and e2 are equal if (e1==null ? e2==null : e1.eq
3 min read
AbstractList get() method in Java with Examples
The get() method of java.util.AbstractList class is used to return the element at the specified position in this list. Syntax: public abstract E get(int index) Parameters: This method takes index of the element as a parameter, the element at which is to be returned. Returns Value: This method returns the element at the specified position in this li
2 min read
AbstractList hashCode() method in Java with Examples
The hashCode() method of java.util.AbstractList class is used to return the hash code value for this list. Syntax: public int hashCode() Returns Value: This method returns the hash code value for this list. Below are the examples to illustrate the hashCode() method. Example 1: // Java program to demonstrate // hashCode() method // for Integer value
2 min read
AbstractList iterator() method in Java with Examples
The iterator() method of java.util.AbstractList class is used to return an iterator over the elements in this list in proper sequence. This implementation returns a straightforward implementation of the iterator interface, relying on the backing list's size(), get(int), and remove(int) methods. Syntax: public Iterator iterator() Returns Value: This
2 min read
AbstractList lastIndexOf() method in Java with Examples
The lastIndexOf() method of java.util.AbstractList class is used to return the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element. More formally, returns the highest index i such that (o==null ? get(i)==null : o.equals(get(i))), or -1 if there is no such index. Syntax: public int last
2 min read
AbstractList indexOf() method in Java with Examples
The indexOf() method of java.util.AbstractList class is used to return the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. More formally, returns the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))), or -1 if there is no such index. Syntax: public int indexOf(
3 min read
AbstractList listIterator() Method in Java with Examples
The listIterator() method of java.util.AbstractList class is used to return a list-iterator containing the same elements as that of the AbstractList in proper and same sequence starting from a specific position or index number which is passed as a parameter to this method. Syntax: ListIterator new_list = AbstractList.listIterator(int index); Parame
2 min read
AbstractList remove() Method in Java with Examples
The remove(int index) method of java.util.AbstractList class is used to remove an element from an abstract list from a specific position or index. Syntax: AbstractList.remove(int index) Parameters: The parameter index is of integer data type and specifies the position of the element to be removed from the AbstractList. Return Value: This method ret
2 min read
AbstractList set() Method in Java with Examples
The set() method of java.util.AbstractList class is used to replace any particular element in the abstract list created using the AbstractList class with another element. This can be done by specifying the position of the element to be replaced and the new element in the parameter of the set() method. Syntax: AbstractList.set(int index, Object elem
2 min read
AbstractList add(E ele) method in Java with Examples
The add(E ele) method of AbstractList class in Java is used to insert the specified element to the end of the current list. Syntax: public boolean add(E ele) Where E is the type of element maintained by this AbstractList collection. Parameter: This method accepts a single parameter ele which represents the element to be inserted at the end of this
2 min read
AbstractList subList() method in Java with Examples
The subList() method of java.util.AbstractList class is used to return a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. (If fromIndex and toIndex are equal, the returned list is empty.) The returned list is backed by this list, so non-structural changes in the returned list are reflected in this
3 min read
AbstractList add(int index, E element) method in Java with Examples
The add(int index, E element) method of AbstractList is used to insert an element at the specified position in this list. The new element is inserted at the specified index in this list. Syntax: public void add(int index, E element) Parameters: This method takes 2 parameters :- index: index at which the specified element is to be inserted element:
2 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Java 8 | ArrayDeque removeIf() method in Java with Examples
The removeIf() method of ArrayDeque is used to remove all those elements from ArrayDeque which satisfies a given predicate filter condition passed as a parameter to the method. This method returns true if some element are removed from the Vector. Java 8 has an important in-built functional interface which is Predicate. Predicate, or a condition che
3 min read
Java lang.Long.lowestOneBit() method in Java with Examples
java.lang.Long.lowestOneBit() is a built-in method in Java which first convert the number to Binary, then it looks for first set bit present at the lowest position then it reset rest of the bits and then returns the value. In simple language, if the binary expression of a number contains a minimum of a single set bit, it returns 2^(first set bit po
3 min read
Java lang.Long.numberOfTrailingZeros() method in Java with Examples
java.lang.Long.numberOfTrailingZeros() is a built-in function in Java which returns the number of trailing zero bits to the right of the lowest order set bit. In simple terms, it returns the (position-1) where position refers to the first set bit from the right. If the number does not contain any set bit(in other words, if the number is zero), it r
3 min read
Java lang.Long.numberOfLeadingZeros() method in Java with Examples
java.lang.Long.numberOfLeadingZeros() is a built-in function in Java which returns the number of leading zero bits to the left of the highest order set bit. In simple terms, it returns the (64-position) where position refers to the highest order set bit from the right. If the number does not contain any set bit(in other words, if the number is zero
3 min read
Java lang.Long.highestOneBit() method in Java with Examples
java.lang.Long.highestOneBit() is a built-in method in Java which first convert the number to Binary, then it looks for the first set bit from the left, then it reset rest of the bits and then returns the value. In simple language, if the binary expression of a number contains a minimum of a single set bit, it returns 2^(last set bit position from
3 min read
Java lang.Long.byteValue() method in Java with Examples
java.lang.Long.byteValue() is a built-in function in Java that returns the value of this Long as a byte. Syntax: public byte byteValue() Parameters: The function does not accept any parameter. Return : This method returns the numeric value represented by this object after conversion to byte type. Examples: Input : 12 Output : 12 Input : 1023 Output
3 min read
Java lang.Long.reverse() method in Java with Examples
java.lang.Long.reverse() is a built-in function in Java which returns the value obtained by reversing the order of the bits in the two's complement binary representation of the specified long value. Syntax: public static long reverse(long num) Parameter : num - the number passed Returns : the value obtained by reversing the order of the bits in the
2 min read
Java Clock tickMinutes() method in Java with Examples
java.time.Clock.tickMinutes(ZoneId zone) method is a static method of Clock class that returns the current instant ticking in whole minutes using the best available system clock and the time-zone of that instant is same as the time-zone passed as a parameter. Nanosecond and second fields of the clock are set to zero to round the instant in the whol
3 min read
Java Clock withZone() method in Java with Examples
The java.time.Clock.withZone(ZoneId zone) method is a method of Clock class which returns a clock copy of clock object on which this method is applied, with a different time-zone. If there is a clock and it is required to change the zone of clock but not other properties, then withZone() method is used. This method takes zone as parameter which is
3 min read
Java.util.concurrent.RecursiveAction class in Java with Examples
RecursiveAction is an abstract class encapsulates a task that does not return a result. It is a subclass of ForkJoinTask, which is an abstract class representing a task that can be executed on a separate core in a multicore system. The RecursiveAction class is extended to create a task that has a void return type. The code that represents the compu
3 min read
Java 8 | IntToDoubleFunction Interface in Java with Examples
The IntToDoubleFunction Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in an int-valued argument and gives a double-valued result. The lambda expression assigned to an object of IntToDoubleFunction type is used to define
1 min read
Java 8 | DoubleToLongFunction Interface in Java with Examples
The DoubleToLongFunction Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in a double-valued argument and gives an long-valued result. The lambda expression assigned to an object of DoubleToLongFunction type is used to defi
1 min read
Java.util.concurrent.Phaser class in Java with Examples
Phaser's primary purpose is to enable synchronization of threads that represent one or more phases of activity. It lets us define a synchronization object that waits until a specific phase has been completed. It then advances to the next phase until that phase concludes. It can also be used to synchronize a single phase, and in that regard, it acts
7 min read
Java.util.concurrent.RecursiveTask class in Java with Examples
RecursiveTask is an abstract class encapsulates a task that returns a result. It is a subclass of ForkJoinTask. The RecursiveTask class is extended to create a task that has a particular return type. The code that represents the computational portion of the task is kept within the compute() method of RecursiveTask. RecursiveTask class is mostly use
2 min read
Java.lang.Short toString() method in Java with Examples
toString(short) The static toString() method of java.lang.Short returns a new String object representing the specified short. The radix is assumed to be 10.This is a static method hence no object of Short class is required for calling this method. Syntax: public static String toString(short b) Parameters: This method accepts a parameter b which is
2 min read