List size() method in Java with Examples
Last Updated :
24 May, 2023
The size() method of the List interface in Java is used to get the number of elements in this list. That is, the list size() method returns the count of elements present in this list container.
Syntax:
public int size()
Parameters: This method does not take any parameters.
Return Value: This method returns the number of elements in this list.
Illustration: Assume it to be an integer list
Input : {3,2,1,5,7}
Output : 5
Example 1:
Java
import java.util.*;
public class GFG {
public static void main(String[] arg)
{
List<Integer> list = new ArrayList<Integer>();
list.add( 1 );
list.add( 2 );
list.add( 3 );
list.add( 4 );
list.add( 5 );
System.out.println( "Before operation: " + list);
int size = list.size();
System.out.println( "Size of list = " + size);
}
}
|
Output
Before operation: [1, 2, 3, 4, 5]
Size of list = 5
Example 2:
Java
import java.util.*;
public class GFG {
public static void main(String[] args)
{
List<String> list = new ArrayList<String>();
list.add( "Geeks" );
list.add( "for" );
list.add( "Geeks" );
System.out.println( "Before operation: " + list);
int size = list.size();
System.out.println( "Size of list = " + size);
}
}
|
Output
Before operation: [Geeks, for, Geeks]
Size of list = 3
Share your thoughts in the comments
Please Login to comment...