Java中的堆栈equals()方法与示例
Java 中 Stack 类的Java Java (Object obj)方法用于验证 Object 与 Stack 的相等性并进行比较。仅当两个 Stack 都包含具有相同顺序的相同元素时,该列表才返回 true。
句法:
first_Stack.equals(second_Stack)
参数:此方法接受一个强制参数second_Stack ,它指的是要与第一个 Stack 进行比较的第二个 Stack。
返回值:如果等式成立并且对象和堆栈都相等,则该方法返回true ,否则返回false 。
以下程序用于说明Java.util.Stack.elements() 方法的工作原理:
方案一:
// 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 stack1 = new Stack();
// 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 stack2 = new Stack();
// 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
方案二:
// 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 stack1 = new Stack();
// 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 stack2 = new Stack();
// 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