Java ConcurrentLinkedDeque push()方法及示例
ConcurrentLinkedDeque 类的 push() 方法是Java中的一个内置函数,它可以在不违反容量限制的情况下立即将一个元素push入该deque所代表的堆栈(换句话说,在该deque的头部),成功后返回true,如果当前没有可用空间,则抛出IllegalStateException。
语法
public void push(E e)
这里,E是这个集合类所维护的元素的类型
由这个集合类维护的元素类型。
参数: 该方法只接受一个参数元素,它将被添加到ConcurntLinkedDeque的头部。
返回值: 该函数没有返回值。
异常: 该方法将抛出以下异常。
- IllegalStateException:如果由于容量的限制,元素不能在这个时候被添加。
- ClassCastException:如果指定元素的类别使其不能被添加到这个deque中。
- NullPointerException:如果指定的元素是空的,而这个deque不允许空元素。
- IllegalArgumentException:如果指定元素的某些属性阻止它被添加到这个deque中。
下面的程序说明了ConcurrentLinkedDeque.push()方法。
程序1: 该程序涉及一个字符类型的ConcurrentLinkedDeque。
// Java program to demonstrate push()
// method of ConcurrentLinkedDeque
import java.util.concurrent.*;
public class GFG {
public static void main(String[] args)
{
// Creating an empty ConcurrentLinkedDeque
ConcurrentLinkedDeque<String> CLD
= new ConcurrentLinkedDeque<String>();
// Use push() method to add elements
CLD.push("Welcome");
CLD.push("To");
CLD.push("Geeks");
CLD.push("For");
CLD.push("Geeks");
// Displaying the ConcurrentLinkedDeque
System.out.println("ConcurrentLinkedDeque: "
+ CLD);
}
}
输出。
ConcurrentLinkedDeque: [Geeks, For, Geeks, To, Welcome]
程序2: 要显示NullPointerException。
// Java program to demonstrate push()
// method of ConcurrentLinkedDeque
import java.util.concurrent.*;
public class GFG {
public static void main(String[] args)
{
// Creating an empty ConcurrentLinkedDeque
ConcurrentLinkedDeque<String> CLD
= new ConcurrentLinkedDeque<String>();
// Displaying the ConcurrentLinkedDeque
System.out.println("ConcurrentLinkedDeque: "
+ CLD);
try {
System.out.println("Trying to add "
+ "null in ConcurrentLinkedDeque");
// Use push() method to null element
CLD.push(null);
}
catch (Exception e) {
System.out.println(e);
}
}
}
输出。
ConcurrentLinkedDeque: []
Trying to add null in ConcurrentLinkedDeque
java.lang.NullPointerException
极客教程