add (Object o) method of List Interface in java.

add (Object o) method of List Interface in java.


Posted in : Core Java Posted on : December 29, 2010 at 6:48 PM Comments : [ 0 ]

In this method you can insert an element into a list.

add (Object o) method of List Interface in java.

In the following example, we will show you the method of adding elements at the end of the list using add (Object o) method of List Interface in java. 

Syntax

boolean add (Object o)

This method returns either True or False value .

In this method you can insert an element  into a list. It inserts an element at the end of the list. In List that supports this method may put limitations on what elements may be added to the list. In particular, some lists may does not allow to add null elements and some other list enforces to restrict on the type of elements that may be added.

parameter description:-

Object o : It takes an Object type element (value) what you want insert into the list.

Example of add (Object o) method

In this example we will show you, how does an add (Object o) method work in List interface. This Example will help you to understand  how an element can be added into the list. Through this example we will show you how an element can be added to a list, and count the number of elements from list before and after adding the elements.

Example:-

package Devmanuals.com;
import java.util.List;
import java.util.ArrayList;
public class ListAddLast {
public static void main (String[] args){
List ls = new ArrayList();
System.out.println("Initially the size of list is " +ls.size());
System.out.println(ls);
System.out.println("After addition of elements (1,2)into the list, the elements are :");
ls.add(1);
ls.add(2);
System.out.println(ls);
System.out.println("The size of list after addition : " + ls.size());
System.out.println("Now insert a new element Ram");
ls.add("Ram");
System.out.println("Then the new Elements of list are : "+ls);
System.out.println("And the size of new list = " + ls.size());
}
}

Output:-

Initially the size of list is 0

[]

After addition of elements (1,2)into the list, the elements are :

[1, 2]

The size of list after addition : 2

Now insert a new element 'Ram'

Then the new Elements of list are : [1, 2, Ram]

And the size of new list = 3

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


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

 
Tutorial Topics