How to Get a Size of Collection in Java?
Last Updated :
15 Oct, 2020
Given a Collection in Java, the task is to find the length or size of the collection.
Examples:
Input: Array_List: [1, 2, 3,4]
Output: 4
Input: Linked_List: [geeks, for, geeks]
Output: 3
The Size of the different collections can be found with the size() method. This method returns the number of elements in this collection. This method does not take any parameters.
Below is the Implementation:
Example 1:
Java
import java.util.*;
public class Example1 {
public static void main(String[] args)
{
List<Integer> Array_List = new ArrayList<Integer>();
Array_List.add( 1 );
Array_List.add( 2 );
Array_List.add( 3 );
Array_List.add( 3 );
int size = Array_List.size();
System.out.println( "Size of list = " + size);
System.out.println( "Array_List = " + Array_List);
}
}
|
Output
Size of list = 4
Array_List = [1, 2, 3, 3]
Example 2:
Java
import java.util.*;
import java.io.*;
class Example2 {
public static void main(String[] args)
{
LinkedList<String> al = new LinkedList<String>();
al.add( "GEEKS" );
al.add( "FOR" );
al.add( "GEEKS" );
int size = al.size();
System.out.println( "Size of the linkedlist = "
+ size);
System.out.println( "Linkedlist = " + al);
}
}
|
Output
Size of the linkedlist = 3
Linkedlist = [GEEKS, FOR, GEEKS]
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...