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:
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
ArrayList<Integer>
arrlist = new ArrayList<Integer>();
arrlist.add( 1 );
arrlist.add( 2 );
arrlist.add( 3 );
arrlist.add( 4 );
arrlist.add( 5 );
System.out.println( "Before operation: "
+ arrlist);
int size = arrlist.size();
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:
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
ArrayList<String>
arrlist = new ArrayList<String>();
arrlist.add( "A" );
arrlist.add( "B" );
arrlist.add( "C" );
System.out.println( "Before operation: "
+ arrlist);
int size = arrlist.size();
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
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
26 Nov, 2018
Like Article
Save Article