Which of the following are interfaces implemented by java util ArrayList

Collection Operations

The operations inherited from Collection all do about what you'd expect them to do, assuming you're already familiar with them. If you're not familiar with them from Collection, now would be a good time to read The Collection Interface section. The remove operation always removes the first occurrence of the specified element from the list. The add and addAll operations always append the new element(s) to the end of the list. Thus, the following idiom concatenates one list to another.

Here's a nondestructive form of this idiom, which produces a third List consisting of the second list appended to the first.

List list3 = new ArrayList(list1); list3.addAll(list2);

Note that the idiom, in its nondestructive form, takes advantage of ArrayList's standard conversion constructor.

And here's an example (JDK 8 and later) that aggregates some names into a List:

List list = people.stream() .map(Person::getName) .collect(Collectors.toList());

Like the Set interface, List strengthens the requirements on the equals and hashCode methods so that two List objects can be compared for logical equality without regard to their implementation classes. Two List objects are equal if they contain the same elements in the same order.

List Interface in Java with Examples

The List interface in Java provides a way to store the ordered collection. It is a child interface of Collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements.

The List interface is found in java.util package and inherits the Collection interface. It is a factory of ListIterator interface. Through the ListIterator, we can iterate the list in forward and backward directions. The implementation classes of the List interface are ArrayList, LinkedList, Stack, and Vector. ArrayList and LinkedList are widely used in Java programming. The Vector class is deprecated since Java 5.

Which of the following are interfaces implemented by java util ArrayList

Declaration: The List interface is declared as:

public interface List<E> extends Collection<E>;

Let us elaborate on creating objects or instances in a List class. Since List is an interface, objects cannot be created of the type list. We always need a class that implements this List in order to create an object. And also, after the introduction of Generics in Java 1.5, it is possible to restrict the type of object that can be stored in the List. Just like several other user-defined ‘interfaces’ implemented by user-defined ‘classes’, List is an ‘interface’, implemented by the ArrayList class, pre-defined in the java.util package.



Syntax: This type of safelist can be defined as:

List<Obj> list = new ArrayList<Obj> ();

Note: Obj is the type of the object to be stored in List

Example:




// Java program to Demonstrate List Interface
// Importing all utility classes
import java.util.*;
// Main class
// ListDemo class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating an object of List interface
// implemented by the ArrayList class
List<Integer> l1 = new ArrayList<Integer>();
// Adding elements to object of List interface
// Custom inputs
l1.add(0, 1);
l1.add(1, 2);
// Print the elements inside the object
System.out.println(l1);
// Now creating another object of the List
// interface implemented ArrayList class
// Declaring object of integer type
List<Integer> l2 = new ArrayList<Integer>();
// Again adding elements to object of List interface
// Custom inputs
l2.add(1);
l2.add(2);
l2.add(3);
// Will add list l2 from 1 index
l1.addAll(1, l2);
System.out.println(l1);
// Removes element from index 1
l1.remove(1);
// Printing the updated List 1
System.out.println(l1);
// Prints element at index 3 in list 1
// using get() method
System.out.println(l1.get(3));
// Replace 0th element with 5
// in List 1
l1.set(0, 5);
// Again printing the updated List 1
System.out.println(l1);
}
}
Output [1, 2] [1, 1, 2, 3, 2] [1, 2, 3, 2] 2 [5, 2, 3, 2]

Now let us perform various operations using List Interface to have a better understanding of the same. We will be discussing the following operations listed below and later on implementing via clean java codes.

Operations in a List interface

Since List is an interface, it can be used only with a class that implements this interface. Now, let’s see how to perform a few frequently used operations on the List.

  • Operation 1: Adding elements to List class using add() method
  • Operation 2: Updating elements in List class using set() method
  • Operation 3: Removing elements using remove() method

Now let us discuss the operations individually and implement the same in the code to grasp a better grip over it.

Operation 1: Adding elements to List class using add() method

In order to add an element to the list, we can use the add() method. This method is overloaded to perform multiple operations based on different parameters.

Parameters: It takes 2 parameters, namely:

  • add(Object): This method is used to add an element at the end of the List.
  • add(int index, Object): This method is used to add an element at a specific index in the List

Example:




// Java Program to Add Elements to a List
// Importing all utility classes
import java.util.*;
// Main class
class GFG {
// Main driver method
public static void main(String args[])
{
// Creating an object of List interface,
// implemented by ArrayList class
List<String> al = new ArrayList<>();
// Adding elements to object of List interface
// Custom elements
al.add("Geeks");
al.add("Geeks");
al.add(1, "For");
// Print all the elements inside the
// List interface object
System.out.println(al);
}
}
Output [Geeks, For, Geeks]

Operation 2: Updating elements

After adding the elements, if we wish to change the element, it can be done using the set() method. Since List is indexed, the element which we wish to change is referenced by the index of the element. Therefore, this method takes an index and the updated element which needs to be inserted at that index.

Example:




// Java Program to Update Elements in a List
// Importing utility classes
import java.util.*;
// Main class
class GFG {
// Main driver method
public static void main(String args[])
{
// Creating an object of List interface
List<String> al = new ArrayList<>();
// Adding elements to object of List class
al.add("Geeks");
al.add("Geeks");
al.add(1, "Geeks");
// Display theinitial elements in List
System.out.println("Initial ArrayList " + al);
// Setting (updating) element at 1st index
// using set() method
al.set(1, "For");
// Print and display the updated List
System.out.println("Updated ArrayList " + al);
}
}
Output Initial ArrayList [Geeks, Geeks, Geeks] Updated ArrayList [Geeks, For, Geeks]

Operation 3: Removing Elements

In order to remove an element from a list, we can use the remove() method. This method is overloaded to perform multiple operations based on different parameters. They are:

Parameters:

  • remove(Object): This method is used to simply remove an object from the List. If there are multiple such objects, then the first occurrence of the object is removed.
  • remove(int index): Since a List is indexed, this method takes an integer value which simply removes the element present at that specific index in the List. After removing the element, all the elements are moved to the left to fill the space and the indices of the objects are updated.

Example:




// Java Program to Remove Elements from a List
// Importing List and ArrayList classes
// from java.util package
import java.util.ArrayList;
import java.util.List;
// Main class
class GFG {
// Main driver method
public static void main(String args[])
{
// Creating List class object
List<String> al = new ArrayList<>();
// Adding elements to the object
// Custom inputs
al.add("Geeks");
al.add("Geeks");
// Adding For at 1st indexes
al.add(1, "For");
// Print the initialArrayList
System.out.println("Initial ArrayList " + al);
// Now remove element from the above list
// present at 1st index
al.remove(1);
// Print the List after removal of element
System.out.println("After the Index Removal " + al);
// Now remove the current object from the updated
// List
al.remove("Geeks");
// Finally print the updated List now
System.out.println("After the Object Removal "
+ al);
}
}
Output Initial ArrayList [Geeks, For, Geeks] After the Index Removal [Geeks, Geeks] After the Object Removal [Geeks]

Iterating over List

Till now we are having a very small input size and we are doing operations manually for every entity. Now let us discuss various ways by which we can iterate over the list to get them working for a larger sample set.

Methods: There are multiple ways to iterate through the List. The most famous ways are by using the basic for loop in combination with a get() method to get the element at a specific index and the advanced for a loop.

Example:




// Java program to Iterate the Elements
// in an ArrayList
// Importing java utility classes
import java.util.*;
// Main class
public class GFG {
// main driver method
public static void main(String args[])
{
// Creating an empty Arraylist of string type
List<String> al = new ArrayList<>();
// Adding elements to above object of ArrayList
al.add("Geeks");
al.add("Geeks");
// Adding element at specified position
// inside list object
al.add(1, "For");
// Using for loop for iteration
for (int i = 0; i < al.size(); i++) {
// Using get() method to
// access particular element
System.out.print(al.get(i) + " ");
}
// New line for better readability
System.out.println();
// Using for-each loop for iteration
for (String str : al)
// Printing all the elements
// which was inside object
System.out.print(str + " ");
}
}
Output Geeks For Geeks Geeks For Geeks

Methods of the List Interface

Since the main concept behind the different types of the lists is the same, the list interface contains the following methods:

Method

Description

add(int index, element) This method is used to add an element at a particular index in the list. When a single parameter is passed, it simply adds the element at the end of the list.
addAll(int index, Collection collection) This method is used to add all the elements in the given collection to the list. When a single parameter is passed, it adds all the elements of the given collection at the end of the list.
size() This method is used to return the size of the list.
clear() This method is used to remove all the elements in the list. However, the reference of the list created is still stored.
remove(int index) This method removes an element from the specified index. It shifts subsequent elements(if any) to left and decreases their indexes by 1.
remove(element) This method is used to remove the first occurrence of the given element in the list.
get(int index) This method returns elements at the specified index.
set(int index, element) This method replaces elements at a given index with the new element. This function returns the element which was just replaced by a new element.
indexOf(element) This method returns the first occurrence of the given element or -1 if the element is not present in the list.
lastIndexOf(element) This method returns the last occurrence of the given element or -1 if the element is not present in the list.
equals(element) This method is used to compare the equality of the given element with the elements of the list.
hashCode() This method is used to return the hashcode value of the given list.
isEmpty() This method is used to check if the list is empty or not. It returns true if the list is empty, else false.
contains(element) This method is used to check if the list contains the given element or not. It returns true if the list contains the element.
containsAll(Collection collection) This method is used to check if the list contains all the collection of elements.
sort(Comparator comp) This method is used to sort the elements of the list on the basis of the given comparator.

Java List vs Set

Both the List interface and the Set interface inherits the Collection interface. However, there exists some differences between them.

List Set
The List is an ordered sequence. The Set is an unordered sequence.
List allows duplicate elements Set doesn’t allow duplicate elements.
Elements by their position can be accessed. Position access to elements is not allowed.
Multiple null elements can be stored. The null element can store only once.
List implementations are ArrayList, LinkedList, Vector, Stack Set implementations are HashSet, LinkedHashSet.

Classes Association with a List Interface

Now let us discuss the classes that implement the List Interface for which first do refer to the pictorial representation below to have a better understanding of the List interface. It is as follows:

Which of the following are interfaces implemented by java util ArrayList

AbstractList, CopyOnWriteArrayList, and the AbstractSequentialList are the classes that implement the List interface. A separate functionality is implemented in each of the mentioned classes. They are as follows:

  1. AbstractList: This class is used to implement an unmodifiable list, for which one needs to only extend this AbstractList Class and implement only the get() and the size() methods.
  2. CopyOnWriteArrayList: This class implements the list interface. It is an enhanced version of ArrayList in which all the modifications(add, set, remove, etc.) are implemented by making a fresh copy of the list.
  3. AbstractSequentialList: This class implements the Collection interface and the AbstractCollection class. This class is used to implement an unmodifiable list, for which one needs to only extend this AbstractList Class and implement only the get() and the size() methods.

We will proceed in this manner.

  • ArrayList
  • Vector
  • Stack
  • LinkedList

Let us discuss them sequentially and implement the same to figure out the working of the classes with the List interface.

Class 1: ArrayList

An ArrayList class which is implemented in the collection framework provides us with dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. Let’s see how to create a list object using this class.

Example:




// Java program to demonstrate the
// creation of list object using the
// ArrayList class
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
// Size of ArrayList
int n = 5;
// Declaring the List with initial size n
List<Integer> arrli
= new ArrayList<Integer>(n);
// Appending the new elements
// at the end of the list
for (int i = 1; i <= n; i++)
arrli.add(i);
// Printing elements
System.out.println(arrli);
// Remove element at index 3
arrli.remove(3);
// Displaying the list after deletion
System.out.println(arrli);
// Printing elements one by one
for (int i = 0; i < arrli.size(); i++)
System.out.print(arrli.get(i) + " ");
}
}
Output [1, 2, 3, 4, 5] [1, 2, 3, 5] 1 2 3 5

Class 2: Vector

Vector is a class that is implemented in the collection framework implements a growable array of objects. Vector implements a dynamic array that means it can grow or shrink as required. Like an array, it contains components that can be accessed using an integer index. Vectors basically fall in legacy classes but now it is fully compatible with collections. Let’s see how to create a list object using this class.

Example:




// Java program to demonstrate the
// creation of list object using the
// Vector class
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
// Size of the vector
int n = 5;
// Declaring the List with initial size n
List<Integer> v = new Vector<Integer>(n);
// Appending the new elements
// at the end of the list
for (int i = 1; i <= n; i++)
v.add(i);
// Printing elements
System.out.println(v);
// Remove element at index 3
v.remove(3);
// Displaying the list after deletion
System.out.println(v);
// Printing elements one by one
for (int i = 0; i < v.size(); i++)
System.out.print(v.get(i) + " ");
}
}
Output [1, 2, 3, 4, 5] [1, 2, 3, 5] 1 2 3 5

Class 3: Stack

Stack is a class that is implemented in the collection framework and extends the vector class models and implements the Stack data structure. The class is based on the basic principle of last-in-first-out. In addition to the basic push and pop operations, the class provides three more functions of empty, search and peek. Let’s see how to create a list object using this class.

Example:




// Java program to demonstrate the
// creation of list object using the
// Stack class
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
// Size of the stack
int n = 5;
// Declaring the List
List<Integer> s = new Stack<Integer>();
// Appending the new elements
// at the end of the list
for (int i = 1; i <= n; i++)
s.add(i);
// Printing elements
System.out.println(s);
// Remove element at index 3
s.remove(3);
// Displaying the list after deletion
System.out.println(s);
// Printing elements one by one
for (int i = 0; i < s.size(); i++)
System.out.print(s.get(i) + " ");
}
}
Output [1, 2, 3, 4, 5] [1, 2, 3, 5] 1 2 3 5

Class 4: LinkedList

LinkedList is a class that is implemented in the collection framework which inherently implements the linked list data structure. It is a linear data structure where the elements are not stored in contiguous locations and every element is a separate object with a data part and address part. The elements are linked using pointers and addresses. Each element is known as a node. Due to the dynamicity and ease of insertions and deletions, they are preferred over the arrays. Let’s see how to create a list object using this class.

Example:




// Java program to demonstrate the
// creation of list object using the
// LinkedList class
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
// Size of the LinkedList
int n = 5;
// Declaring the List with initial size n
List<Integer> ll = new LinkedList<Integer>();
// Appending the new elements
// at the end of the list
for (int i = 1; i <= n; i++)
ll.add(i);
// Printing elements
System.out.println(ll);
// Remove element at index 3
ll.remove(3);
// Displaying the list after deletion
System.out.println(ll);
// Printing elements one by one
for (int i = 0; i < ll.size(); i++)
System.out.print(ll.get(i) + " ");
}
}
Output [1, 2, 3, 4, 5] [1, 2, 3, 5] 1 2 3 5

Which of the following are interfaces implemented by java util ArrayList




Article Tags :
Java
Java - util package
Java-Collections
java-list
Practice Tags :
Java
Java-Collections

ArrayList in Java

ArrayList is a part of collection framework and is present in java.util package. It provides us with dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. This class is found in java.util package.

Which of the following are interfaces implemented by java util ArrayList

Illustration:

Which of the following are interfaces implemented by java util ArrayList

Example: The following implementation demonstrates how to create and use an ArrayList.






// Java program to demonstrate the
// working of ArrayList in Java
import java.io.*;
import java.util.*;
class ArrayListExample {
public static void main(String[] args)
{
// Size of the
// ArrayList
int n = 5;
// Declaring the ArrayList with
// initial size n
ArrayList<Integer> arrli
= new ArrayList<Integer>(n);
// Appending new elements at
// the end of the list
for (int i = 1; i <= n; i++)
arrli.add(i);
// Printing elements
System.out.println(arrli);
// Remove element at index 3
arrli.remove(3);
// Displaying the ArrayList
// after deletion
System.out.println(arrli);
// Printing elements one by one
for (int i = 0; i < arrli.size(); i++)
System.out.print(arrli.get(i) + " ");
}
}
Output [1, 2, 3, 4, 5] [1, 2, 3, 5] 1 2 3 5

Since ArrayList is a dynamic array and we do not have to specify the size while creating it, the size of the array automatically increases when we dynamically add and remove items. Though the actual library implementation may be more complex, the following is a very basic idea explaining the working of the array when the array becomes full and if we try to add an item:

  • Creates a bigger-sized memory on heap memory (for example memory of double size).
  • Copies the current memory elements to the new memory.
  • New item is added now as there is bigger memory available now.
  • Delete the old memory.

Important Features:

  • ArrayList inherits AbstractList class and implements the List interface.
  • ArrayList is initialized by the size. However, the size is increased automatically if the collection grows or shrinks if the objects are removed from the collection.
  • Java ArrayList allows us to randomly access the list.
  • ArrayList can not be used for primitive types, like int, char, etc. We need a wrapper class for such cases.
  • ArrayList in Java can be seen as a vector in C++.
  • ArrayList is not Synchronized. Its equivalent synchronized class in Java is Vector.

Let’s understand the Java ArrayList in depth. Look at the below image:

Which of the following are interfaces implemented by java util ArrayList

In the above illustration, AbstractList, CopyOnWriteArrayList, and the AbstractSequentialList are the classes that implement the list interface. A separate functionality is implemented in each of the mentioned classes. They are:

  1. AbstractList: This class is used to implement an unmodifiable list, for which one needs to only extend this AbstractList Class and implement only the get() and the size() methods.
  2. CopyOnWriteArrayList: This class implements the list interface. It is an enhanced version of ArrayList in which all the modifications(add, set, remove, etc.) are implemented by making a fresh copy of the list.
  3. AbstractSequentialList: This class implements the Collection interface and the AbstractCollection class. This class is used to implement an unmodifiable list, for which one needs to only extend this AbstractList Class and implement only the get() and the size() methods.

Constructors in the ArrayList

In order to create an ArrayList, we need to create an object of the ArrayList class. The ArrayList class consists of various constructors which allow the possible creation of the array list. The following are the constructors available in this class:

1. ArrayList(): This constructor is used to build an empty array list. If we wish to create an empty ArrayList with the name arr, then, it can be created as:

ArrayList arr = new ArrayList();

2. ArrayList(Collection c): This constructor is used to build an array list initialized with the elements from the collection c. Suppose, we wish to create an ArrayList arr which contains the elements present in the collection c, then, it can be created as:

ArrayList arr = new ArrayList(c);

3. ArrayList(int capacity): This constructor is used to build an array list with initial capacity being specified. Suppose we wish to create an ArrayList with the initial size being N, then, it can be created as:

ArrayList arr = new ArrayList(N);

Methods in Java ArrayList

Method Description
add(int index, Object element) This method is used to insert a specific element at a specific position index in a list.
add(Object o) This method is used to append a specific element to the end of a list.
addAll(Collection C) This method is used to append all the elements from a specific collection to the end of the mentioned list, in such an order that the values are returned by the specified collection’s iterator.
addAll(int index, Collection C) Used to insert all of the elements starting at the specified position from a specific collection into the mentioned list.
clear() This method is used to remove all the elements from any list.
clone() This method is used to return a shallow copy of an ArrayList.
contains?(Object o) Returns true if this list contains the specified element.
ensureCapacity?(int minCapacity) Increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument.
forEach?(Consumer<? super E> action) Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.
get?(int index) Returns the element at the specified position in this list.
indexOf(Object O) The index the first occurrence of a specific element is either returned, or -1 in case the element is not in the list.
isEmpty?() Returns true if this list contains no elements.
lastIndexOf(Object O) The index of the last occurrence of a specific element is either returned or -1 in case the element is not in the list.
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.
remove?(Object o) Removes the first occurrence of the specified element from this list, if it is present.
removeAll?(Collection c) Removes from this list all of its elements that are contained in the specified collection.
removeIf?(Predicate filter) Removes all of the elements of this collection that satisfy the given predicate.
removeRange?(int fromIndex, int toIndex) Removes from this list all of the elements whose index is between fromIndex, inclusive, and toIndex, exclusive.
retainAll?(Collection<?> c) Retains only the elements in this list that are contained in the specified collection.
set?(int index, E element) Replaces the element at the specified position in this list with the specified element.
size?() Returns the number of elements in this list.
spliterator?() Creates a late-binding and fail-fast Spliterator over the elements in this list.
subList?(int fromIndex, int toIndex) Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.
toArray() This method is used to return an array containing all of the elements in the list in the correct order.
toArray(Object[] O) It is also used to return an array containing all of the elements in this list in the correct order same as the previous method.
trimToSize() This method is used to trim the capacity of the instance of the ArrayList to the list’s current size.

Note: You can also create a generic ArrayList:

// Creating generic integer ArrayList ArrayList<Integer> arrli = new ArrayList<Integer>();

Let’s see how to perform some basics operations on the ArrayList as listed which we are going to discuss further alongside implementing every operation.

  • Adding element to List
  • Changing elements
  • Removing elements
  • Iterating elements

Operation 1: Adding Elements

In order to add an element to an ArrayList, we can use the add() method. This method is overloaded to perform multiple operations based on different parameters. They are as follows:

  • add(Object): This method is used to add an element at the end of the ArrayList.
  • add(int index, Object): This method is used to add an element at a specific index in the ArrayList.

Example:




// Java Program to Add elements to An ArrayList
// Importing all utility classes
import java.util.*;
// Main class
class GFG {
// Main driver method
public static void main(String args[])
{
// Creating an Array of string type
ArrayList<String> al = new ArrayList<>();
// Adding elements to ArrayList
// Custom inputs
al.add("Geeks");
al.add("Geeks");
// Here we are mentioning the index
// at which it is to be added
al.add(1, "For");
// Printing all the elements in an ArrayList
System.out.println(al);
}
}
Output: [Geeks, For, Geeks]

Operation 2: Changing Elements

After adding the elements, if we wish to change the element, it can be done using the set() method. Since an ArrayList is indexed, the element which we wish to change is referenced by the index of the element. Therefore, this method takes an index and the updated element which needs to be inserted at that index.

Example




// Java Program to Change elements in ArrayList
// Importing all utility classes
import java.util.*;
// main class
class GFG {
// Main driver method
public static void main(String args[])
{
// Creating an Arratlist object of string type
ArrayList<String> al = new ArrayList<>();
// Adding elements to Arraylist
// Custom input elements
al.add("Geeks");
al.add("Geeks");
// Adding specifying the index to be added
al.add(1, "Geeks");
// Printing the Arraylist elements
System.out.println("Initial ArrayList " + al);
// Setting element at 1st index
al.set(1, "For");
// Printing the updated Arraylist
System.out.println("Updated ArrayList " + al);
}
}
Output: Initial ArrayList [Geeks, Geeks, Geeks] Updated ArrayList [Geeks, For, Geeks]

Operation 3: Removing Elements

In order to remove an element from an ArrayList, we can use the remove() method. This method is overloaded to perform multiple operations based on different parameters. They are as follows:

  • remove(Object): This method is used to simply remove an object from the ArrayList. If there are multiple such objects, then the first occurrence of the object is removed.
  • remove(int index): Since an ArrayList is indexed, this method takes an integer value which simply removes the element present at that specific index in the ArrayList. After removing the element, all the elements are moved to the left to fill the space and the indices of the objects are updated.

Example




// Java program to Remove Elements in ArrayList
// Importing all utility classes
import java.util.*;
// Main class
class GFG {
// Main driver method
public static void main(String args[])
{
// Creating an object of arraylist class
ArrayList<String> al = new ArrayList<>();
// Adding elements to ArrayList
// Custom addition
al.add("Geeks");
al.add("Geeks");
// Adding element at specific index
al.add(1, "For");
// Printing all elements of ArrayList
System.out.println("Initial ArrayList " + al);
// Removing element from above ArrayList
al.remove(1);
// Printing the updated Arraylist elements
System.out.println("After the Index Removal " + al);
// Removing this word element in ArrayList
al.remove("Geeks");
// Now printing updated ArrayList
System.out.println("After the Object Removal "
+ al);
}
}
Output: Initial ArrayList [Geeks, For, Geeks] After the Index Removal [Geeks, Geeks] After the Object Removal [Geeks]

Operation 4: Iterating the ArrayList

There are multiple ways to iterate through the ArrayList. The most famous ways are by using the basic for loop in combination with a get() method to get the element at a specific index and the advanced for loop.

Example




// Java program to Iterate the elements
// in an ArrayList
// Importing all utility classes
import java.util.*;
// Main class
class GFG {
// Main driver method
public static void main(String args[])
{
// Creating an Arraylist of string type
ArrayList<String> al = new ArrayList<>();
// Adding elements to ArrayList
// using standard add() method
al.add("Geeks");
al.add("Geeks");
al.add(1, "For");
// Using the Get method and the
// for loop
for (int i = 0; i < al.size(); i++) {
System.out.print(al.get(i) + " ");
}
System.out.println();
// Using the for each loop
for (String str : al)
System.out.print(str + " ");
}
}
Output: Geeks For Geeks Geeks For Geeks

Must Read: Array vs ArrayList in Java

Which of the following are interfaces implemented by java util ArrayList




Article Tags :
Java
Technical Scripter
Java - util package
Java-ArrayList
Java-Collections
java-list
Practice Tags :
Java
Java-Collections

Collections in Java

  1. Java Collection Framework
  2. Hierarchy of Collection Framework
  3. Collection interface
  4. Iterator interface

The Collection in Java is a framework that provides an architecture to store and manipulate the group of objects.

Java Collections can achieve all the operations that you perform on a data such as searching, sorting, insertion, manipulation, and deletion.

Java Collection means a single unit of objects. Java Collection framework provides many interfaces (Set, List, Queue, Deque) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).

What is Collection in Java

A Collection represents a single unit of objects, i.e., a group.

What is a framework in Java

  • It provides readymade architecture.
  • It represents a set of classes and interfaces.
  • It is optional.

What is Collection framework

The Collection framework represents a unified architecture for storing and manipulating a group of objects. It has:

  1. Interfaces and its implementations, i.e., classes
  2. Algorithm

Do You Know?
  • What are the two ways to iterate the elements of a collection?
  • What is the difference between ArrayList and LinkedList classes in collection framework?
  • What is the difference between ArrayList and Vector classes in collection framework?
  • What is the difference between HashSet and HashMap classes in collection framework?
  • What is the difference between HashMap and Hashtable class?
  • What is the difference between Iterator and Enumeration interface in collection framework?
  • How can we sort the elements of an object? What is the difference between Comparable and Comparator interfaces?
  • What does the hashcode() method?
  • What is the difference between Java collection and Java collections?

Hierarchy of Collection Framework

Let us see the hierarchy of Collection framework. The java.util package contains all the classes and interfaces for the Collection framework.

Which of the following are interfaces implemented by java util ArrayList

Methods of Collection interface

There are many methods declared in the Collection interface. They are as follows:

No.MethodDescription
1public boolean add(E e)It is used to insert an element in this collection.
2public boolean addAll(Collection<? extends E> c)It is used to insert the specified collection elements in the invoking collection.
3public boolean remove(Object element)It is used to delete an element from the collection.
4public boolean removeAll(Collection<?> c)It is used to delete all the elements of the specified collection from the invoking collection.
5default boolean removeIf(Predicate<? super E> filter)It is used to delete all the elements of the collection that satisfy the specified predicate.
6public boolean retainAll(Collection<?> c)It is used to delete all the elements of invoking collection except the specified collection.
7public int size()It returns the total number of elements in the collection.
8public void clear()It removes the total number of elements from the collection.
9public boolean contains(Object element)It is used to search an element.
10public boolean containsAll(Collection<?> c)It is used to search the specified collection in the collection.
11public Iterator iterator()It returns an iterator.
12public Object[] toArray()It converts collection into array.
13public <T> T[] toArray(T[] a)It converts collection into array. Here, the runtime type of the returned array is that of the specified array.
14public boolean isEmpty()It checks if collection is empty.
15default Stream<E> parallelStream()It returns a possibly parallel Stream with the collection as its source.
16default Stream<E> stream()It returns a sequential Stream with the collection as its source.
17default Spliterator<E> spliterator()It generates a Spliterator over the specified elements in the collection.
18public boolean equals(Object element)It matches two collections.
19public int hashCode()It returns the hash code number of the collection.

Iterator interface

Iterator interface provides the facility of iterating the elements in a forward direction only.

Methods of Iterator interface

There are only three methods in the Iterator interface. They are:

No.MethodDescription
1public boolean hasNext()It returns true if the iterator has more elements otherwise it returns false.
2public Object next()It returns the element and moves the cursor pointer to the next element.
3public void remove()It removes the last elements returned by the iterator. It is less used.