Tuesday 1 April 2014

Add Element to the List

boolean add(E e)
    Appends the specified element to the end of this list.

import java.util.*;
class ListAdd{
 public static void main(String args[]){
  List<String> myList = new ArrayList<> ();
  
  /* Add Elements to myList */
  myList.add("Hi");
  System.out.println("Elements in myList are");
  System.out.println(myList);
  
  myList.add("How");
  System.out.println("Elements in myList are");
  System.out.println(myList);
  
  myList.add("Are");
  System.out.println("Elements in myList are");
  System.out.println(myList);
  
  myList.add("You");
  System.out.println("Elements in myList are");
  System.out.println(myList);
 }
}

Output
Elements in myList are
[Hi]
Elements in myList are
[Hi, How]
Elements in myList are
[Hi, How, Are]
Elements in myList are
[Hi, How, Are, You]

1. throws UnsupportedOperationException if the add operation is not supported by this list

import java.util.*;
class ListAddUnsupport{
 public static void main(String args[]){
  List<String> myList = new ArrayList<> ();
  List<String> unModifyList;
  
  /* Add Elements to myList */
  myList.add("Hi");
  myList.add("How");
  myList.add("Are");
  myList.add("You");
  
  unModifyList = Collections.unmodifiableList(myList);
  System.out.println("Elements in unModifyList are");
  System.out.println(unModifyList);
  
  /* Trying to add Element to unmodifiable list */
  unModifyList.add("abcd");
 }
}
Since “ unModifyList” is a unmodifiable list, so adding element to the unmodifiable list cause “UnsupportedOperationException”.

Elements in unModifyList are
[Hi, How, Are, You]
Exception in thread "main" java.lang.UnsupportedOperationException
        at java.util.Collections$UnmodifiableCollection.add(Unknown Source)
        at ListAddUnsupport.main(ListAddUnsupport.java:18)


2. throws ClassCastException if the class of the specified element prevents it from being added to this list

3. throws NullPointerException if the specified element is null and this
list does not permit null elements

4. throws IllegalArgumentException if some property of this element
prevents it from being added to this list



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment