Java中的ConcurrentLinkedDeque push()方法及示例

Java中的ConcurrentLinkedDeque push()方法及示例

ConcurrentLinkedDeque 类中的 push() 方法是Java中的内置函数,它将一个元素推入表示此双端队列的堆栈(换句话说,推到此双端队列的头部),如果可以立即执行而不违反容量限制,则返回true并抛出IllegalStateException异常。

语法:

public void push(E e)

这里,E是集合类维护的元素类型。

参数: 这个方法只接受一个参数element,它将被添加到ConcurentLinkedDeque的头部。

返回值: 这个函数没有返回值。

异常: 该方法将抛出以下异常。

  • IllegalStateException:如果由于容量限制,此时无法添加元素。
  • ClassCastException:如果指定元素的类禁止将其添加到此deque中。
  • NullPointerException:如果指定的元素为null并且这个deque不允许null元素。
  • IllegalArgumentException:如果指定元素的某些属性禁止将其添加到这个deque中。

下面的程序演示了ConcurrentLinkedDeque.push()方法:

程序1: 这个程序涉及到一个Character类型的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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程