Java ArrayDeque

Trong hướng dẫn này, chúng ta sẽ tìm hiểu về lớp ArrayDeque và các phương thức của nó với sự trợ giúp của các ví dụ. Ngoài ra, chúng ta sẽ học cách sử dụng mảng deque để triển khai một ngăn xếp.

Trong Java, chúng ta có thể sử dụng ArrayDequelớp để triển khai các cấu trúc dữ liệu hàng đợi và deque bằng cách sử dụng mảng.

Các giao diện được thực hiện bởi ArrayDeque

Các ArrayDequelớp thực hiện hai giao diện này:

  • Java Queue Interface
  • Java Deque Interface

Tạo ArrayDeque

Để tạo một mảng deque, chúng ta phải nhập java.util.ArrayDequegói.

Đây là cách chúng ta có thể tạo một mảng deque trong Java:

ArrayDeque<Type> animal = new ArrayDeque<>();

Ở đây, Kiểu cho biết kiểu của mảng. Ví dụ,

// Creating String type ArrayDeque
ArrayDeque<String> animals = new ArrayDeque<>();

// Creating Integer type ArrayDeque
ArrayDeque<Integer> age = new ArrayDeque<>();

Các phương thức của ArrayDeque

Các ArrayDequelớp học cung cấp triển khai cho tất cả các phương pháp hiện tại Queuevà Dequegiao diện.

Chèn các phần tử vào Deque

1. Thêm các phần tử bằng add (), addFirst () và addLast ()

  • add() – inserts the specified element at the end of the array deque
  • addFirst() – inserts the specified element at the beginning of the array deque
  • addLast() – inserts the specified at the end of the array deque (equivalent to add())

Lưu ý: Nếu deque mảng đầy, tất cả các phương pháp này add()addFirst()và addLast()ném IllegalStateException.

Ví dụ,

import java.util.ArrayDeque;

class Main {
    public static void main(String[] args) {
        ArrayDeque<String> animals= new ArrayDeque<>();

        // Using add()
        animals.add("Dog");

        // Using addFirst()
        animals.addFirst("Cat");

        // Using addLast()
        animals.addLast("Horse");
        System.out.println("ArrayDeque: " + animals);
    }
}

Đầu ra

ArrayDeque: [Cat, Dog, Horse]

2. Chèn các phần tử bằng cách sử dụng offer (), offerFirst () và offerLast ()

  • offer() – inserts the specified element at the end of the array deque
  • offerFirst() – inserts the specified element at the beginning of the array deque
  • offerLast() – inserts the specified element at the end of the array deque

Lưu ý: offer() , offerFirst()và offerLast()lợi nhuận truenếu phần tử được chèn thành công; nếu mảng deque đầy, các phương thức này trả về false.

Ví dụ,

import java.util.ArrayDeque;

class Main {
    public static void main(String[] args) {
        ArrayDeque<String> animals= new ArrayDeque<>();
        // Using offer()
        animals.offer("Dog");

        // Using offerFirst()
        animals.offerFirst("Cat");

        // Using offerLast()
        animals.offerLast("Horse");
        System.out.println("ArrayDeque: " + animals);
    }
}

Đầu ra

ArrayDeque: [Cat, Dog, Horse]

Lưu ý: Nếu mảng deque đầy

  • the add() method will throw an exception
  • the offer() method returns false

Truy cập các phần tử ArrayDeque

1. Truy cập các phần tử bằng getFirst () và getLast ()

  • getFirst() – returns the first element of the array deque
  • getLast() – returns the last element of the array deque

Lưu ý: Nếu deque mảng trống getFirst()và getLast()ném NoSuchElementException.

Ví dụ,

import java.util.ArrayDeque;

class Main {
    public static void main(String[] args) {
        ArrayDeque<String> animals= new ArrayDeque<>();
        animals.add("Dog");
        animals.add("Cat");
        animals.add("Horse");
        System.out.println("ArrayDeque: " + animals);

        // Get the first element
        String firstElement = animals.getFirst();
        System.out.println("First Element: " + firstElement);

        // Get the last element
        String lastElement = animals.getLast();
        System.out.println("Last Element: " + lastElement);
    }
}

Đầu ra

ArrayDeque: [Dog, Cat, Horse]
First Element: Dog
Last Element: Horse

2. Truy cập các phần tử bằng phương thức peek (), peekFirst () và peekLast ()

  • peek() – returns the first element of the array deque
  • peekFirst() – returns the first element of the array deque (equivalent to peek())
  • peekLast() – returns the last element of the array deque

Ví dụ,

import java.util.ArrayDeque;

class Main {
    public static void main(String[] args) {
        ArrayDeque<String> animals= new ArrayDeque<>();
        animals.add("Dog");
        animals.add("Cat");
        animals.add("Horse");
        System.out.println("ArrayDeque: " + animals);

        // Using peek()
        String element = animals.peek();
        System.out.println("Head Element: " + element);

        // Using peekFirst()
        String firstElement = animals.peekFirst();
        System.out.println("First Element: " + firstElement);

        // Using peekLast
        String lastElement = animals.peekLast();
        System.out.println("Last Element: " + lastElement);
    }
}

Đầu ra

ArrayDeque: [Dog, Cat, Horse]
Head Element: Dog
First Element: Dog
Last Element: Horse

Lưu ý: Nếu deque mảng trống peek()peekFirst()và getLast()ném NoSuchElementException.

Loại bỏ các phần tử ArrayDeque

1. Loại bỏ các phần tử bằng phương thức remove (), removeFirst (), removeLast ()

  • remove() – returns and removes an element from the first element of the array deque
  • remove(element) – returns and removes the specified element from the head of the array deque
  • removeFirst() – returns and removes the first element from the array deque (equivalent to remove())
  • removeLast() – returns and removes the last element from the array deque

Lưu ý: Nếu deque mảng rỗng, remove()removeFirst()và removeLast()phương pháp ném một ngoại lệ. Ngoài ra, remove(element)ném một ngoại lệ nếu phần tử không được tìm thấy.

Ví dụ,

import java.util.ArrayDeque;

class Main {
    public static void main(String[] args) {
        ArrayDeque<String> animals= new ArrayDeque<>();
        animals.add("Dog");
        animals.add("Cat");
        animals.add("Cow");
        animals.add("Horse");
        System.out.println("ArrayDeque: " + animals);

        // Using remove()
        String element = animals.remove();
        System.out.println("Removed Element: " + element);

        System.out.println("New ArrayDeque: " + animals);

        // Using removeFirst()
        String firstElement = animals.removeFirst();
        System.out.println("Removed First Element: " + firstElement);

        // Using removeLast()
        String lastElement = animals.removeLast();
        System.out.println("Removed Last Element: " + lastElement);
    }
}

Đầu ra

ArrayDeque: [Dog, Cat, Cow, Horse]
Removed Element: Dog
New ArrayDeque: [Cat, Cow, Horse]
Removed First Element: Cat
Removed Last Element: Horse

2. Loại bỏ các phần tử bằng cách sử dụng phương thức thăm dò (), thăm dò ý kiến ​​() và thăm dò ý kiến ​​()

  • poll() – returns and removes the first element of the array deque
  • pollFirst() – returns and removes the first element of the array deque (equivalent to poll())
  • pollLast() – returns and removes the last element of the array deque

Lưu ý: Nếu deque mảng rỗng, poll()pollFirst()và pollLast()lợi nhuận nullnếu phần tử không được tìm thấy.

Ví dụ,

import java.util.ArrayDeque;

class Main {
    public static void main(String[] args) {
        ArrayDeque<String> animals= new ArrayDeque<>();
        animals.add("Dog");
        animals.add("Cat");
        animals.add("Cow");
        animals.add("Horse");
        System.out.println("ArrayDeque: " + animals);

        // Using poll()
        String element = animals.poll();
        System.out.println("Removed Element: " + element);
        System.out.println("New ArrayDeque: " + animals);

        // Using pollFirst()
        String firstElement = animals.pollFirst();
        System.out.println("Removed First Element: " + firstElement);

        // Using pollLast()
        String lastElement = animals.pollLast();
        System.out.println("Removed Last Element: " + lastElement);
    }
}

Đầu ra

ArrayDeque: [Dog, Cat, Cow, Horse]
Removed Element: Dog
New ArrayDeque: [Cat, Cow, Horse]
Removed First Element: Cat
Removed Last Element: Horse

3. Loại bỏ phần tử: sử dụng phương thức clear ()

Để xóa tất cả các phần tử khỏi mảng deque, chúng ta sử dụng clear()phương thức. Ví dụ,

import java.util.ArrayDeque;

class Main {
    public static void main(String[] args) {
        ArrayDeque<String> animals= new ArrayDeque<>();
        animals.add("Dog");
        animals.add("Cat");
        animals.add("Horse");
        System.out.println("ArrayDeque: " + animals);

        // Using clear()
        animals.clear();

        System.out.println("New ArrayDeque: " + animals);
    }
}

Đầu ra

ArrayDeque: [Dog, Cat, Horse]
New ArrayDeque: []

Lặp lại ArrayDeque

  • iterator() – returns an iterator that can be used to iterate over the array deque
  • descendingIterator() – returns an iterator that can be used to iterate over the array deque in reverse order

Để sử dụng các phương pháp này, chúng ta phải nhập java.util.Iteratorgói. Ví dụ,

import java.util.ArrayDeque;
import java.util.Iterator;

class Main {
    public static void main(String[] args) {
        ArrayDeque<String> animals= new ArrayDeque<>();
        animals.add("Dog");
        animals.add("Cat");
        animals.add("Horse");

        System.out.print("ArrayDeque: ");

        // Using iterator()
        Iterator<String> iterate = animals.iterator();
        while(iterate.hasNext()) {
            System.out.print(iterate.next());
            System.out.print(", ");
        }

        System.out.print("\nArrayDeque in reverse order: ");
        // Using descendingIterator()
        Iterator<String> desIterate = animals.descendingIterator();
        while(desIterate.hasNext()) {
            System.out.print(desIterate.next());
            System.out.print(", ");
        }
    }
}

Đầu ra

ArrayDeque: [Dog, Cat, Horse]
ArrayDeque in reverse order: [Horse, Cat, Dog]

Các phương pháp khác

MethodsDecfscriptions
element()Returns an element from the head of the array deque.
contains(element)Searches the array deque for the specified element.
If the element is found, it returns true, if not it returns false.
size()Returns the length of the array deque.
toArray()Converts array deque to array and returns it.
clone()Creates a copy of the array deque and returns it.

ArrayDeque dưới dạng ngăn xếp

Để triển khai ngăn xếp LIFO (Last-In-First-Out) trong Java, bạn nên sử dụng một deque trên lớp Stack . Các ArrayDequelớp học có khả năng là nhanh hơn so với Stacklớp.

ArrayDeque cung cấp các phương pháp sau có thể được sử dụng để triển khai ngăn xếp.

  • push() – adds an element to the top of the stack
  • peek() – returns an element from the top of the stack
  • pop() – returns and removes an element from the top of the stack

Ví dụ,

import java.util.ArrayDeque;

class Main {
    public static void main(String[] args) {
        ArrayDeque<String> stack = new ArrayDeque<>();

        // Add elements to stack
        stack.push("Dog");
        stack.push("Cat");
        stack.push("Horse");
        System.out.println("Stack: " + stack);

        // Access element from top of stack
        String element = stack.peek();
        System.out.println("Accessed Element: " + element);

        // Remove elements from top of stack
        String remElement = stack.pop();
        System.out.println("Removed element: " + remElement);
    }
}

Đầu ra

Stack: [Horse, Cat, Dog]
Accessed Element: Horse
Removed Element: Horse

ArrayDeque Vs. Lớp danh sách liên kết

Cả hai ArrayDequevà Java LinkedList thực hiện Dequegiao diện. Tuy nhiên, tồn tại một số khác biệt giữa chúng.

  • LinkedList supports null elements, whereas ArrayDeque doesn’t.
  • Each node in a linked list includes links to other nodes. That’s why LinkedList requires more storage than ArrayDeque.
  • If you are implementing the queue or the deque data structure, an ArrayDeque is likely to faster than a LinkedList.








Gõ tìm kiếm nhanh...