Tuesday 1 April 2014

remove : Remove Element from the List

boolean remove(Object o)
    Removes the first occurrence of the specified element from this list. Returns true if the list change after performing the operation else false.


import java.util.*;
class ListRemove{
 public static void main(String args[]){
  List<String> myList = new ArrayList<> ();
  
  /* Add Elements to myList */
  myList.add("Hi");
  myList.add("How");
  myList.add("Are");
  myList.add("You");
  myList.add("How");
  
  System.out.println("Elements in the list are");
  System.out.println(myList+"\n");
  
  /* remove Element from list */
  System.out.println("Removing the element \"How\" from the list " + myList.remove("How"));
  
  System.out.println("Elements in the list After removing \"How\" ");
  System.out.println(myList +"\n");
  
  /* remove Element from list */
  System.out.println("Removing the element \"abcd\" from the list " + myList.remove("abcd"));
  
  System.out.println("Elements in the list After removing \"abcd\" ");
  System.out.println(myList+"\n");
 }
}

Output
Elements in the list are
[Hi, How, Are, You, How]

Removing the element "How" from the list true
Elements in the list After removing "How"
[Hi, Are, You, How]

Removing the element "abcd" from the list false
Elements in the list After removing "abcd"
[Hi, Are, You, How]

1. remove method throws ClassCastException if the type of the specified element is incompatible with this list

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

3. remove method throws UnsupportedOperationException if the remove operation is not supported by this list




Prevoius                                                 Next                                                 Home

No comments:

Post a Comment