当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Deque removeFirstOccurrence()用法及代码示例


Deque 接口的 removeFirstOccurrence() 方法用于从双端队列中删除给定元素的第一次出现。如果双端队列中没有元素,则它保持不变。如果 deque 包含指定的元素,它可能返回 true。

用法:

boolean removeFirstOccurrence(Object o)

参数:

以上只需要一个参数:

  1. 需要从给定双端队列中删除 d 的元素 'o'。

返回:

如果从双端队列中删除特定元素,则上述方法返回 true。

抛出:

  • ClassCastException- 如果给定元素的类与给定双端队列不兼容。
  • NullPointerException - 如果指定的元素已经为空并且给定的双端队列不允许空元素。

例子1

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

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

输出:

The character is already present? true
The final deque is given as:
a
b
d

例子2

import java.util.ArrayDeque;
import java.util.Deque;
public class JavaDequeremoveFirstoccurrenceExample2 {
    public static void main(String[] args) {	
    	Deque<Integer> deque = new ArrayDeque<>();
	    deque.push(2);
	    deque.push(5);
	    deque.push(6);
	    deque.push(7);
	    Boolean val = deque.removeFirstOccurrence(5);
	    System.out.println("The intger value is already preesnt? "+val);
	  System.out.println("The final deque is given as:");   
	  for (Integer integer:deque) {
		System.out.println(integer);
	}
   }
}

输出:

The integer value is already preesnt? true
The final deque is given as:
7
6
2

例子3

import java.util.ArrayDeque;
import java.util.Deque;
public class JavaDequeremoveFirstoccurrenceExample3 {
    public static void main(String[] args) {	
    	Deque<Float> deque = new ArrayDeque<>();
	    deque.push(66.8f);
	    deque.push(50.8f);
	    deque.push(63.4f);
	    deque.push(71.2f);
	    Boolean val = deque.removeFirstOccurrence(5);
	    System.out.println("The float value is already preesnt? "+val);
	  System.out.println("The final deque is given as:");   
	 for (Float float1:deque) {
		System.out.println(float1);
	}
   }
}

输出:

The float value is already preesnt? false
The final deque is given as:
71.2
63.4
50.8
66.8




相关用法


注:本文由纯净天空筛选整理自 Java Deque removeFirstOccurrence() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。