Friday 11 April 2014

removeLastOccurrence : Removes the last occurrence of the element

boolean removeLastOccurrence(Object o)
Removes the last occurrence of the specified element from this deque. Returns true if this deque contained the specified element or if this deque changed as a result of the call.

import java.util.*;

class DequeRemoveLastOccurrence{
 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 Last Occurence of 10 " + myDeque.removeLastOccurrence(10));
  System.out.println("Elements in the myDeque are " +myDeque);
  
  System.out.println("\nRemoving the Last Occurence of 88 " + myDeque.removeLastOccurrence(88));
  System.out.println("Elements in the myDeque are " +myDeque); 
 }
}

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

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

Removing the Last Occurence of 88 false
Elements in the myDeque are [10, 20, 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 DequeRemoveLastOccurrenceNull{
 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 DequeRemoveLastOccurrenceNull.main(DequeRemoveLastOccurrenceNull.java:16)


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment