Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

List add(E ele) method in Java with Examples

  • Last Updated : 11 Dec, 2018

The add(E ele) method of List interface in Java is used to insert the specified element to the end of the current list.

Syntax:

public boolean add(E ele)

Parameter: This method accepts a single parameter ele which represents the element to be inserted at the end of this list.

Return Value: The function returns a boolean value True if the element is successfully inserted in the List otherwise it returns False.

Exceptions:



  • UnsupportedOperationException – It throws this exception if the add() operation is not supported by this list.
  • ClassCastException – It throws this exception if the class of the specified element prevents it from being added to this list.
  • NullPointerException – It throws this exception if the specified element is null and this list does not permit null elements.
  • IllegalArgumentException – It throws this exception if some property of this element prevents it from being added to this list.

Below programs illustrate the RoleList.add(Object obj) method:

Program 1:




// Java code to illustrate add(Object o)
import java.io.*;
import java.util.*;
  
public class ArrayListDemo {
    public static void main(String[] args)
    {
  
        // create an empty list with an initial capacity
        List<Integer> list = new ArrayList<Integer>(5);
  
        // use add() method to add elements in the list
        list.add(15);
        list.add(20);
        list.add(25);
  
        // prints all the elements available in list
        for (Integer number : list) {
            System.out.println("Number = " + number);
        }
    }
}
Output:
Number = 15
Number = 20
Number = 25

Program 2:




// Java code to illustrate add(Object o)
import java.io.*;
import java.util.*;
  
public class ArrayListDemo {
    public static void main(String[] args)
    {
  
        // create an empty list with an initial capacity
        List<String> list = new ArrayList<String>(5);
  
        // use add() method to add elements in the list
        list.add("Geeks");
        list.add("For");
        list.add("Geeks");
  
        // prints all the elements available in list
        for (String str : list) {
            System.out.print(str + " ");
        }
    }
}
Output:
Geeks For Geeks

Reference: https://docs.oracle.com/javase/7/docs/api/java/util/List.html#add(E)




My Personal Notes arrow_drop_up
Recommended Articles
Page :