size ( ) method of List Interface in java.

size ( ) method of List Interface in java.


Posted in : Core Java Posted on : January 12, 2011 at 7:07 PM Comments : [ 0 ]

In this section we will discuss how can we find the number of elements in any list using size ( ) method of List interface in java.

size ( ) method of List Interface in java.

In this section we will discuss how can we find the number of elements in any list using size ( ) method of List interface in java.

Syntax

int size ( )

This method counts the total element contained by an existing list and returned it.

Using this method you can find the total number of elements of an existing list. It returns the number of elements of a list. An existing list which contains more than Integer.MAX_VALUE elements, it returns Integer.MAX_VALUE.

Parameter Description 

It does not take any argument, only returns integer (number of elements of a list) value.

Example of size( ) method 

In this example we will show you how does size( ) method works in List interface. This example will help you to understand for finding number of elements in a list. Through this example we will show you adding of elements in a list, and check is list empty or contains elements and then, we will find how many elements in a list i.e. size of list.

Example:-

package Devmanuals.com;
import java.util.List;
import java.util.ArrayList;
public class ListSize {
public static void main (String args []){
int size;
ArrayList al=new ArrayList();
al.add(1);
al.add(2);
al.add(3);
al.add(4);
al.add(5);
al.add(6);
System.out.println("Is List empty ? "+al.isEmpty());
if (al != null) {
System.out.println("List is : "+al);
}
elseSystem.out.println("List have no elements " +al);
size= al.size();
System.out.println("Size of list : "+size);
//When remove the elements from list
al.clear();
System.out.println("Is List empty ? "+al.isEmpty());
System.out.println("List have no elements " +al);
System.out.println("Size of list : " +al.size());
}
} 

Output :

Is List empty ? false

List is : [1, 2, 3, 4, 5, 6]

Size of list : 6

Is List empty ? true

List have no elements []

Size of list : 0

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics