Java Stack equals()方法及实例

Java Stack equals()方法及实例

Java.util.Stack .equals(Object obj)方法是用来验证一个对象和一个Stack的平等性,并对它们进行比较。只有当两个堆栈都包含相同的元素且顺序相同时,该列表才会返回真。

语法

first_Stack.equals(second_Stack)

参数: 该方法接受一个强制性参数second_Stack,它指的是要与第一个Stack进行比较的第二个Stack。

返回值: 如果相等成立,并且对象和堆栈都相等,该方法返回真,否则返回假。

下面的程序用来说明java.util.Stack.elements()方法的工作。

程序1 :

// Java code to illustrate the equals() method
import java.util.*;
  
public class Stack_Demo {
    public static void main(String[] args)
    {
  
        // Creating an empty Stack
        Stack<String> stack1 = new Stack<String>();
  
        // Inserting elements into the table
        stack1.add("Geeks");
        stack1.add("4");
        stack1.add("Geeks");
        stack1.add("Welcomes");
        stack1.add("You");
  
        // Displaying the Stack
        System.out.println("The Stack is: "
                           + stack1);
  
        // Creating an empty Stack
        Stack<String> stack2 = new Stack<String>();
  
        // Inserting elements into the table
        stack2.add("Geeks");
        stack2.add("4");
        stack2.add("Geeks");
        stack2.add("Welcomes");
        stack2.add("You");
  
        // Displaying the Stack
        System.out.println("The Stack is: "
                           + stack2);
  
        System.out.println("Are both of them equal? "
                           + stack1.equals(stack2));
    }
}

输出:

The Stack is: [Geeks, 4, Geeks, Welcomes, You]
The Stack is: [Geeks, 4, Geeks, Welcomes, You]
Are both of them equal? true

程序2 :

// Java code to illustrate the equals() method
import java.util.*;
  
public class Stack_Demo {
    public static void main(String[] args)
    {
  
        // Creating an empty Stack
        Stack<Integer> stack1 = new Stack<Integer>();
  
        // Inserting elements into the table
        stack1.add(10);
        stack1.add(15);
        stack1.add(20);
        stack1.add(25);
        stack1.add(30);
  
        // Displaying the Stack
        System.out.println("The Stack is: " + stack1);
  
        // Creating an empty Stack
        Stack<Integer> stack2 = new Stack<Integer>();
  
        // Inserting elements into the table
        stack2.add(10);
        stack2.add(15);
        stack2.add(20);
        stack2.add(25);
        stack2.add(30);
        stack2.add(40);
  
        // Displaying the Stack
        System.out.println("The Stack is: " + stack2);
  
        System.out.println("Are both of them equal? "
                           + stack1.equals(stack2));
    }
}

输出:

The Stack is: [10, 15, 20, 25, 30]
The Stack is: [10, 15, 20, 25, 30, 40]
Are both of them equal? false

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程