📜  Java中的堆栈类

📅  最后修改于: 2022-05-13 01:55:37.634000             🧑  作者: Mango

Java中的堆栈类

Java Collection 框架提供了一个 Stack 类,该类对Stack 数据结构进行建模和实现。该课程基于后进先出的基本原则。除了基本的push和pop操作外,该类还提供了empty、search和peek三个功能。该类也可以说是对 Vector 的扩展,并将该类视为具有上述五个函数的堆栈。该类也可以称为 Vector 的子类。下图显示了 Stack 类的层次结构

Java中的堆栈类

该类支持一个默认构造函数Stack() ,用于创建一个空堆栈

宣言:

public class Stack extends Vector

所有实现的接口:

  • Serializable:如果要序列化和反序列化,它是类必须实现的标记接口。
  • Cloneable:这是Java中的一个接口,需要由一个类实现以允许其对象被克隆。
  • Iterable此接口表示可迭代的对象集合——意味着可以迭代。
  • Collection一个 Collection 表示一组称为元素的对象。 Collection 接口用于传递需要最大通用性的对象集合。
  • List List 接口提供了一种存储有序集合的方法。它是 Collection 的子接口。
  • RandomAccess:这是 List 实现使用的标记接口,用于指示它们支持快速(通常是恒定时间)随机访问。

如何创建堆栈?

为了创建堆栈,我们必须导入Java.util.stack包并使用该类的 Stack() 构造函数。下面的示例创建一个空堆栈。

这里 E 是 Object 的类型。

例子:

Java
// Java code for stack implementation
 
import java.io.*;
import java.util.*;
 
class Test
{  
    // Pushing element on the top of the stack
    static void stack_push(Stack stack)
    {
        for(int i = 0; i < 5; i++)
        {
            stack.push(i);
        }
    }
     
    // Popping element from the top of the stack
    static void stack_pop(Stack stack)
    {
        System.out.println("Pop Operation:");
 
        for(int i = 0; i < 5; i++)
        {
            Integer y = (Integer) stack.pop();
            System.out.println(y);
        }
    }
 
    // Displaying element on the top of the stack
    static void stack_peek(Stack stack)
    {
        Integer element = (Integer) stack.peek();
        System.out.println("Element on stack top: " + element);
    }
     
    // Searching element in the stack
    static void stack_search(Stack stack, int element)
    {
        Integer pos = (Integer) stack.search(element);
 
        if(pos == -1)
            System.out.println("Element not found");
        else
            System.out.println("Element is found at position: " + pos);
    }
 
 
    public static void main (String[] args)
    {
        Stack stack = new Stack();
 
        stack_push(stack);
        stack_pop(stack);
        stack_push(stack);
        stack_peek(stack);
        stack_search(stack, 2);
        stack_search(stack, 6);
    }
}


Java
// Java program to add the
// elements in the stack
import java.io.*;
import java.util.*;
 
class StackDemo {
   
      // Main Method
    public static void main(String[] args)
    {
 
        // Default initialization of Stack
        Stack stack1 = new Stack();
 
        // Initialization of Stack
        // using Generics
        Stack stack2 = new Stack();
 
        // pushing the elements
        stack1.push(4);
        stack1.push("All");
        stack1.push("Geeks");
 
        stack2.push("Geeks");
        stack2.push("For");
        stack2.push("Geeks");
 
          // Printing the Stack Elements
        System.out.println(stack1);
        System.out.println(stack2);
    }
}


Java
// Java program to demonstrate the accessing
// of the elements from the stack
import java.util.*;
import java.io.*;
 
public class StackDemo {
 
      // Main Method
    public static void main(String args[])
    {
        // Creating an empty Stack
        Stack stack = new Stack();
 
        // Use push() to add elements into the Stack
        stack.push("Welcome");
        stack.push("To");
        stack.push("Geeks");
        stack.push("For");
        stack.push("Geeks");
 
        // Displaying the Stack
        System.out.println("Initial Stack: " + stack);
 
        // Fetching the element at the head of the Stack
        System.out.println("The element at the top of the"
                           + " stack is: " + stack.peek());
 
        // Displaying the Stack after the Operation
        System.out.println("Final Stack: " + stack);
    }
}


Java
// Java program to demonstrate the removing
// of the elements from the stack
import java.util.*;
import java.io.*;
 
public class StackDemo {
    public static void main(String args[])
    {
        // Creating an empty Stack
        Stack stack = new Stack();
 
        // Use add() method to add elements
        stack.push(10);
        stack.push(15);
        stack.push(30);
        stack.push(20);
        stack.push(5);
 
        // Displaying the Stack
        System.out.println("Initial Stack: " + stack);
 
        // Removing elements using pop() method
        System.out.println("Popped element: "
                           + stack.pop());
        System.out.println("Popped element: "
                           + stack.pop());
 
        // Displaying the Stack after pop operation
        System.out.println("Stack after pop operation "
                           + stack);
    }
}


Java
// A Java Program to show implementation
// of Stack using ArrayDeque
 
import java.util.*;
 
class GFG {
    public static void main (String[] args) {
        Deque stack = new ArrayDeque();
        stack.push('A');
        stack.push('B');
        System.out.println(stack.peek());
        System.out.println(stack.pop());
    }
}


输出:

Pop Operation:
4
3
2
1
0
Element on stack top: 4
Element is found at position: 3
Element not found

对 Stack 类执行各种操作

1. 添加元素:为了向栈中添加元素,我们可以使用push() 方法。这个push()操作将元素放在堆栈的顶部。

Java

// Java program to add the
// elements in the stack
import java.io.*;
import java.util.*;
 
class StackDemo {
   
      // Main Method
    public static void main(String[] args)
    {
 
        // Default initialization of Stack
        Stack stack1 = new Stack();
 
        // Initialization of Stack
        // using Generics
        Stack stack2 = new Stack();
 
        // pushing the elements
        stack1.push(4);
        stack1.push("All");
        stack1.push("Geeks");
 
        stack2.push("Geeks");
        stack2.push("For");
        stack2.push("Geeks");
 
          // Printing the Stack Elements
        System.out.println(stack1);
        System.out.println(stack2);
    }
}

输出:

[4, All, Geeks]
[Geeks, For, Geeks]

2. 访问元素:要检索或获取堆栈的第一个元素或堆栈顶部的元素,我们可以使用peek()方法。检索到的元素不会从堆栈中删除或移除。

Java

// Java program to demonstrate the accessing
// of the elements from the stack
import java.util.*;
import java.io.*;
 
public class StackDemo {
 
      // Main Method
    public static void main(String args[])
    {
        // Creating an empty Stack
        Stack stack = new Stack();
 
        // Use push() to add elements into the Stack
        stack.push("Welcome");
        stack.push("To");
        stack.push("Geeks");
        stack.push("For");
        stack.push("Geeks");
 
        // Displaying the Stack
        System.out.println("Initial Stack: " + stack);
 
        // Fetching the element at the head of the Stack
        System.out.println("The element at the top of the"
                           + " stack is: " + stack.peek());
 
        // Displaying the Stack after the Operation
        System.out.println("Final Stack: " + stack);
    }
}

输出:

Initial Stack: [Welcome, To, Geeks, For, Geeks]
The element at the top of the stack is: Geeks
Final Stack: [Welcome, To, Geeks, For, Geeks]

3. 移除元素:要从堆栈中弹出一个元素,我们可以使用pop()方法。元素从栈顶弹出并从栈顶移除。

Java

// Java program to demonstrate the removing
// of the elements from the stack
import java.util.*;
import java.io.*;
 
public class StackDemo {
    public static void main(String args[])
    {
        // Creating an empty Stack
        Stack stack = new Stack();
 
        // Use add() method to add elements
        stack.push(10);
        stack.push(15);
        stack.push(30);
        stack.push(20);
        stack.push(5);
 
        // Displaying the Stack
        System.out.println("Initial Stack: " + stack);
 
        // Removing elements using pop() method
        System.out.println("Popped element: "
                           + stack.pop());
        System.out.println("Popped element: "
                           + stack.pop());
 
        // Displaying the Stack after pop operation
        System.out.println("Stack after pop operation "
                           + stack);
    }
}

输出:

Initial Stack: [10, 15, 30, 20, 5]
Popped element: 5
Popped element: 20
Stack after pop operation [10, 15, 30]

Stack 类中的方法

METHOD

DESCRIPTION

empty()

It returns true if nothing is on the top of the stack. Else, returns false.

peek()

Returns the element on the top of the stack, but does not remove it.

pop()

Removes and returns the top element of the stack. An ‘EmptyStackException’ 

An exception is thrown if we call pop() when the invoking stack is empty.

push(Object element)

Pushes an element on the top of the stack.

search(Object element)

It determines whether an object exists in the stack. If the element is found,

It returns the position of the element from the top of the stack. Else, it returns -1.

从类Java.util.Vector 继承的方法

METHOD

DESCRIPTION

add(Object obj)Appends the specified element to the end of this Vector.
add(int index, Object obj)Inserts the specified element at the specified position in this Vector.
addAll(Collection c)

Appends all of the elements in the specified Collection to the end of this Vector, 

in the order that they are returned by the specified Collection’s Iterator.

addAll(int index, Collection c)Inserts all the elements in the specified Collection into this Vector at the specified position.
addElement(Object o)Adds the specified component to the end of this vector, increasing its size by one.
capacity()Returns the current capacity of this vector.
clear()Removes all the elements from this Vector.
clone()Returns a clone of this vector.
contains(Object o)Returns true if this vector contains the specified element.
containsAll(Collection c)Returns true if this Vector contains all the elements in the specified Collection.
copyInto(Object []array)Copies the components of this vector into the specified array.
elementAt(int index)Returns the component at the specified index.
elements()Returns an enumeration of the components of this vector.
ensureCapacity(int minCapacity)

Increases the capacity of this vector, if necessary, to ensure that it can hold 

at least the number of components specified by the minimum capacity argument.

equals()Compares the specified Object with this Vector for equality.
firstElement()Returns the first component (the item at index 0) of this vector.
get(int index)Returns the element at the specified position in this Vector.
hashCode()Returns the hash code value for this Vector.
indexOf(Object o)

Returns the index of the first occurrence of the specified element in this vector, or -1 

if this vector does not contain the element.

indexOf(Object o, int index)Returns the index of the first occurrence of the specified element in this vector, searching forwards from the index, or returns -1 if the element is not found.
insertElementAt(Object o, int index)Inserts the specified object as a component in this vector at the specified index.
isEmpty()Tests if this vector has no components.
iterator()Returns an iterator over the elements in this list in proper sequence.
lastElement()Returns the last component of the vector.
lastIndexOf(Object o)

Returns the index of the last occurrence of the specified element in this vector, or -1

 If this vector does not contain the element.

lastIndexOf(Object o, int index)

Returns the index of the last occurrence of the specified element in this vector, 

searching backward from the index, or returns -1 if the element is not found.

listIterator()Returns a list iterator over the elements in this list (in proper sequence).
listIterator(int index)

Returns a list iterator over the elements in this list (in proper sequence), 

starting at the specified position in the list.

remove(int index)Removes the element at the specified position in this Vector.
remove(Object o)Removes the first occurrence of the specified element in this Vector If the Vector does not contain the element, it is unchanged.
removeAll(Collection c)Removes from this Vector all of its elements that are contained in the specified Collection.
removeAllElements()Removes all components from this vector and sets its size to zero.
removeElement(Object o)Removes the first (lowest-indexed) occurrence of the argument from this vector.
removeElementAt(int index)Deletes the component at the specified index.
removeRange(int fromIndex, int toIndex)Removes from this list all the elements whose index is between fromIndex, inclusive, and toIndex, exclusive.
retainAll(Collection c)Retains only the elements in this Vector that are contained in the specified Collection.
set(int index, Object o)Replaces the element at the specified position in this Vector with the specified element.
setElementAt(Object o, int index)Sets the component at the specified index of this vector to be the specified object.
setSize(int newSize)Sets the size of this vector.
size()Returns the number of components in this vector.
subList(int fromIndex, int toIndex)Returns a view of the portion of this List between fromIndex, inclusive, and toIndex, exclusive.
toArray()Returns an array containing all of the elements in this Vector in the correct order.
toArray(Object []array)

Returns an array containing all of the elements in this Vector in the correct order; the runtime

 type of the returned array is that of the specified array.

toString()Returns a string representation of this Vector, containing the String representation of each element.
trimToSize()Trims the capacity of this vector to be the vector’s current size.

注意:请注意, Java中的 Stack 类是遗留类,继承自Java中的 Vector 。它是一个线程安全的类,因此当我们不需要线程安全时会产生开销。推荐使用ArrayDeque 用于堆栈实现,因为它在单线程环境中更有效。

Java

// A Java Program to show implementation
// of Stack using ArrayDeque
 
import java.util.*;
 
class GFG {
    public static void main (String[] args) {
        Deque stack = new ArrayDeque();
        stack.push('A');
        stack.push('B');
        System.out.println(stack.peek());
        System.out.println(stack.pop());
    }
}

输出:

B
B