Which field or method of the ArrayList class will return the number of elements stored in the ArrayList?

Why ArrayList is better than Array?

The limitation with array is that it has a fixed length so if it is full you cannot add any more elements to it, likewise if there are number of elements gets removed from it the memory consumption would be the same as it doesn’t shrink.

On the other ArrayList can dynamically grow and shrink after addition and removal of elements [See the images below]. Apart from these benefits ArrayList class enables us to use predefined methods of it which makes our task easy. Let’s see the diagrams to understand the addition and removal of elements from ArrayList and then we will see the programs.

Adding Element in ArrayList at specified position:

Removing Element from ArrayList:

There is a list of several tutorials on ArrayList at the end of this guide, refer it to understand and learn ArrayList concept fully.

Java ArrayList

last modified November 12, 2021

Java ArrayList tutorial shows how to work with ArrayList collection in Java. Located in the java.util package, ArrayList is an important collection of the Java collections framework.

Java collections framework is a unified architecture for representing and manipulating collections, enabling collections to be manipulated independently of implementation details. A collection is an object that represents a group of objects.

ArrayList Methods In Java

The following table lists all the methods that are provided by the ArrayList class.

MethodMethod PrototypeMethod Description
Addboolean add[E e]Adds given element e to the end of the list.
void add[int index, E element]Adds given element ‘element’ at the specified position ‘index’.
AddAllboolean addAll [Collection extends E> c]Adds all the elements in the given collection c to the end of the list.
boolean addAll [int index, Collection extends E> c]Adds all the elements in the given collection c at the position specified by the ‘index’ in the list.
Clearvoid clear[]Clears the list by removing all the elements from the list.
CloneObject clone[]Makes a shallow copy of the given ArrayList.
Containsboolean contains[Object o]Checks if the list contains the given element ‘o’. Returns true if the element is present.
ensureCapacityvoid ensureCapacity [int minCapacity]Increases the capacity of the ArrayList to ensure it has the minCapacity.
GetE get[int index]Returns the element in the list present at the position specified by ‘index’.
indexOfint indexOf[Object o]Returns the index of the first occurrence of element o in the list. -1 if element o is not present in the list.
isEmptyboolean isEmpty[]Checks if the given list is empty.
IteratorIterator iterator[]Returns an iterator to traverse over the list elements in the proper sequence.
lastIndexOfint lastIndexOf[Object o]Returns the index of the last occurrence of the specified element o in the list. -1 if the element is not present in the list.
listIteratorListIterator listIterator[]Returns list iterator to traverse over the elements of the given list.
ListIterator listIterator[int index]Returns the list iterator starting from the specified position ‘index’ to traverse over the elements of the given list.
removeE remove[int index]Deletes element at the ‘index’ in the ArrayList.
boolean remove[Object o]Deletes the first occurrence of element o from the list.
removeAllboolean removeAll[Collection c]Removes all the elements from the list that match the elements in given collection c.
removeRangeprotected void removeRange [int fromIndex, int toIndex]Removes elements specified in the given range, fromIndex [inclusive] to toIndex [exclusive] from the list.
retainAllboolean retainAll[Collection c]Retains those elements in the list that match the elements in the given collection c.
setE set[int index, E element]Sets the element value at given ‘index’ to the new value given by ‘element’.
sizeint size[]Returns the total number of elements or length of the list.
subListList subList[int fromIndex, int toIndex]Returns a subList between given range, fromIndex to toIndex for the given list.
toArrayObject[] toArray[]Converts the given list into an array.
T[] toArray[T[] a]Converts the given list into an array of the type given by a.
trimToSizevoid trimToSize[]Trims the ArrayList capacity to the size or number of elements present in the list.

Next, we will discuss each of these methods from the ArrayList function API in detail and present programming examples. After discussing all the methods listed above, we will also take up some specific operations that are carried out using ArrayLists which are not a part of the ArrayList function API.

ArrayList add

I

Prototype: boolean add [E e]
Parameters: e=> Element to be added to the ArrayList.
Return Value: true=> Element successfully added.
Description: Adds the given element e to the end of the list.

II.

Prototype: void add [int index, E element]

Parameters:

index=> Position at which the element is to be added.
Element=> Element to be added to the ArrayList.

Return Value: void

Description: Adds given element ‘element’ at the specified position ‘index’ by shifting the element at that position and subsequent elements to the right.

Exceptions: IndexOutOfBoundsException => If the specified index is out of the range.

ArrayList addAll

I

Prototype: boolean addAll [Collection c]
Parameters: c=> Collection whose elements match with those of ArrayList and are to be removed.
Return Value: true=> If the ArrayList is altered by the operation.

Description: Removes all the elements from the list that match the elements in the given collection c. As a result, the elements remaining are shifted to the left of the list.

Exceptions: ClassCastException => Class is not the same as that of the specified collection which implies class is incompatible.
NullPointerException => If the given collection c is null; or if c has a null element and it is not allowed by the collection.

ArrayList removeRange

Prototype: protected void removeRange [int fromIndex, int toIndex]
Parameters: fromIndex=> Index of the starting element of the range to be removed.
toIndex=> Index of the element after the last element in the range to be removed.
Return Value: void
Description: Removes elements specified in the given range, fromIndex [inclusive] to toIndex [exclusive] from the list. This operation shortens the length of the list by [toIndex-fromIndex]. This operation has no effect in case fromIndex = toIndex.
Exceptions: IndexOutOfBoundsException=> If any of the indices [fromIndex or toIndex] is out of bounds.

Let us implement a Java program to demonstrate some of these remove methods that we discussed above.

import java.util.*; class Main{ public static void main[String args[]]{ //create an ArrayList ArrayList city_List=new ArrayList[Arrays.asList["Delhi","Mumbai","Chennai", "Kolkata", "Pune", "Hyderabad"]]; //print the list System.out.println["Initial ArrayList:" + city_List]; //remove element at index 2 city_List.remove[2]; //print the list System.out.println["\nArrayList after removing element at index 2:" + city_List]; //remove the element "Kolkata" city_List.remove["Kolkata"]; //print the list System.out.println["\nArrayList after removing element -> Kolkata:" + city_List]; //create new list ArrayList newCities=new ArrayList[Arrays.asList["Delhi","Hyderabad"]]; //call removeAll to remove elements contained in newCities list. city_List.removeAll[newCities]; //print the list System.out.println["\nArrayList after call to removeAll:" + city_List]; } }

Output:

Initial ArrayList:[Delhi, Mumbai, Chennai, Kolkata, Pune, Hyderabad
ArrayList after removing element at index 2:[Delhi, Mumbai, Kolkata, Pune, Hyderabad]
ArrayList after removing element -> Kolkata:[Delhi, Mumbai, Pune, Hyderabad]
ArrayList after call to removeAll:[Mumbai, Pune]

Java ArrayList Implementation

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.

Illustration:

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



Java




// 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 arrli
= new ArrayList[n];
// Appending new elements at
// the end of the list
for [int i = 1; i 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 arrli = new ArrayList[];

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




// 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 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




// 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 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




// 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 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




// 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 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




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

ArrayList size[] method in Java with Examples

The size[] method of java.util.ArrayList class is used to get the number of elements in this list.

Syntax:

public int size[]

Returns Value: This method returns the number of elements in this list.

Below are the examples to illustrate the size[] method.

Example 1:






// Java program to demonstrate
// size[] method
// for Integer value
import java.util.*;
public class GFG1 {
public static void main[String[] argv]
throws Exception
{
try {
// Creating object of ArrayList
ArrayList
arrlist = new ArrayList[];
// Populating arrlist1
arrlist.add[1];
arrlist.add[2];
arrlist.add[3];
arrlist.add[4];
arrlist.add[5];
// print arrlist
System.out.println["Before operation: "
+ arrlist];
// getting total size of arrlist
// using size[] method
int size = arrlist.size[];
// print the size of arrlist
System.out.println["Size of list = "
+ size];
}
catch [IndexOutOfBoundsException e] {
System.out.println["Exception thrown: "
+ e];
}
}
}
Output: Before operation: [1, 2, 3, 4, 5] Size of list = 5

Example 2:




// Java program to demonstrate
// size[] method
// for String value
import java.util.*;
public class GFG1 {
public static void main[String[] argv]
throws Exception
{
try {
// Creating object of ArrayList
ArrayList
arrlist = new ArrayList[];
// Populating arrlist1
arrlist.add["A"];
arrlist.add["B"];
arrlist.add["C"];
// print arrlist
System.out.println["Before operation: "
+ arrlist];
// getting total size of arrlist
// using size[] method
int size = arrlist.size[];
// print the size of arrlist
System.out.println["Size of list = "
+ size];
}
catch [IndexOutOfBoundsException e] {
System.out.println["Exception thrown: "
+ e];
}
}
}
Output: Before operation: [A, B, C] Size of list = 3




Article Tags :
Java
Java - util package
Java-ArrayList
Java-Collections
Java-Functions
Practice Tags :
Java
Java-Collections
Read Full Article

Video liên quan

Bài mới nhất

Chủ Đề