Collection Interface add() Method

Collection Interface add() Method


Posted in : Java Posted on : November 24, 2010 at 6:37 PM Comments : [ 0 ]

This method used to add object to the invoking collection. It return true if the object added in the invoking collection otherwise return false

Collection Interface add() Method:

This method used to add object to the invoking collection. It return true if the object added in the invoking collection otherwise return false(if object already exist in the collection or collection does not allow duplicates).

Syntax :

boolean add(Object ob);

Example :

import java.util.ArrayList;
import java.util.List;
import java.util.Collection;

public class CollectionInterfaceAddMethodExample {

public static void main(String[] args) {
  Collection collection = new ArrayList(); 
  boolean result1 = collection.add("Ankit");  
  if(result1==true){
	  System.out.println("First Element added successfully.");
  }
  else{
	  System.out.println("First Element not added successfully.");
  }
  boolean result2 = collection.add("Deepak");  
  if(result2==true){
	  System.out.println("Second Element added successfully.");
  }
  else{
	  System.out.println("Second Element not added successfully.");
  }  	  	  
  System.out.print("Elements Of the Array List");
  System.out.println(collection + ".");		      	      
}
}

In this example we have create ArrayList object and add elements in the collection object and check the results.

Output :

First Element added successfully.
Second Element added successfully.
Elements Of the Array List[Ankit, Deepak].

Download This example code

Go to Topic «PreviousHomeNext»

Your Comment:


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

 
Tutorial Topics