Friday, 11 April 2014

removeFirstOccurrence : Removes the first occurrence of the element

boolean removeFirstOccurrence(Object o)
Removes the first occurrence of the specified element. Returns true if this deque contained the specified element or equivalently, if this deque changed as a result of the call.

import java.util.*;

class DequeRemoveFirstOccurrence{
 public static void main(String args[]){
  Deque<Integer> myDeque = new LinkedList<Integer> ();
  
  /* Add Elements to the myDeque */
  myDeque.add(10);
  myDeque.add(20);
  myDeque.add(10);
  myDeque.add(40);
  
  System.out.println("Elements in the myDeque are " +myDeque);
  
  System.out.println("\nRemoving the First Occurence of 10 " + myDeque.removeFirstOccurrence(10));
  System.out.println("Elements in the myDeque are " +myDeque);
  
  System.out.println("\nRemoving the First Occurence of 88 " + myDeque.removeFirstOccurrence(88));
  System.out.println("Elements in the myDeque are " +myDeque); 
 }
}

Output
Elements in the myDeque are [10, 20, 10, 40]

Removing the First Occurence of 10 true
Elements in the myDeque are [20, 10, 40]

Removing the First Occurence of 88 false
Elements in the myDeque are [20, 10, 40]

1. throws ClassCastException if the class of the specified element is incompatible with this deque

2. throws NullPointerException if the specified element is null and this
deque does not permit null elements
import java.util.*;
import java.util.concurrent.ConcurrentLinkedDeque;

class DequeRemoveFirstOccurrenceNull{
 public static void main(String args[]){
  Deque<Integer> myDeque = new ConcurrentLinkedDeque<Integer> ();
  
  /* Add Elements to the myDeque */
  myDeque.add(10);
  myDeque.add(20);
  myDeque.add(10);
  myDeque.add(40);
  
  System.out.println("Elements in the myDeque are " +myDeque);
  
  myDeque.removeFirstOccurrence(null);
 }
}

Output
Elements in the myDeque are [10, 20, 10, 40]
Exception in thread "main" java.lang.NullPointerException
   at java.util.concurrent.ConcurrentLinkedDeque.checkNotNull(ConcurrentLinkedDeque.java:800)
   at java.util.concurrent.ConcurrentLinkedDeque.removeFirstOccurrence(ConcurrentLinkedDeque.java:1044)
   at DequeRemoveFirstOccurrenceNull.main(DequeRemoveFirstOccurrenceNull.java:16)


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment