當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Deque removeLastOccurrence()用法及代碼示例


Deque 接口的 removeLastOccurrence() 方法用於從給定的雙端隊列中刪除最後一次出現的指定元素。如果雙端隊列中沒有元素,則它保持不變。如果指定的元素存在於雙端隊列中,則上述方法返回 true。

用法:

boolean removeLastOccurrence(Object o)

參數:

以上隻需要一個參數:

  1. 需要從給定雙端隊列中刪除的元素 'o'。

返回:

上述方法用於在指定元素被移除時返回true。

拋出:

  • ClassCastException- 如果指定的元素與給定的雙端隊列不兼容。
  • NullPointerException - 如果指定的元素已經為空並且給定的雙端隊列不允許空元素。

例子1

import java.util.ArrayDeque;
import java.util.Deque;

public class JavaDequeremoveLastOccurrenceExample1 {
   public static void main(String[] args) {
	   Deque<Character> deque = new ArrayDeque<>();
	    deque.push('a'); 
	    deque.push('d');
	    deque.push('c');
	    deque.push('b');
	    deque.push('a');
	    boolean val = deque.removeLastOccurrence('a');
	    System.out.println("The value is already present in the deque:"+val);
	  System.out.println("The final deque is given as:");   
	  for (Character character:deque) {
		System.out.println(character);
	   }
	}
}

輸出:

The value is already present in the deque:true
The final deque is given as:
a
b
c
d

例子2

import java.util.ArrayDeque;
import java.util.Deque;

public class JavaDequeremoveLastOccurrenceExample2 {
   public static void main(String[] args) {
	   Deque<Long> deque = new ArrayDeque<>();
	    deque.add(23l); 
	    deque.add(45l);
	    deque.add(63l);
	    deque.add(45l);  
	boolean val = deque.removeLastOccurrence(55l);
	    System.out.println("The value is already present in the deque:"+val);
	  System.out.println("The final deque is given as:");   
	 for (Long long1:deque) {
		System.out.println(long1);
	  }
   }
}

輸出:

The value is already present in the deque:false
The final deque is given as:
23
45
63
45

例子3

import java.util.ArrayDeque;
import java.util.Deque;
public class JavaDequeremoveLastOccurrenceExample3 {
   public static void main(String[] args) {
	   Deque<Float> deque = new ArrayDeque<>();
	    deque.add(55.8f); 
	    deque.add(22.3f);
	    deque.add(89f);
	    deque.add(22.3f);  
	boolean val = deque.removeLastOccurrence(22.3f);
	  System.out.println("The value is already present in the deque:"+val);
	  System.out.println("The final deque is given as:");   
	for (Float float1:deque) {
		System.out.println(float1);
	}
   }
}

輸出:

The value is already present in the deque:true
The final deque is given as:
55.8
22.3
89.0




相關用法


注:本文由純淨天空篩選整理自 Java Deque removeLastOccurrence() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。