当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Stack equals()用法及代码示例


Java中的Stack类的Java.util.Stack.equals(Object obj)方法用于验证Object与Stack的相等性并进行比较。仅当两个Stack包含相同顺序的相同元素时,列表才返回true。

用法:

first_Stack.equals(second_Stack)

参数:此方法接受强制性参数second_Stack,该参数表示第二个要与第一个堆栈进行比较的堆栈。


返回值:如果相等相等且对象和Stack相等,则该方法返回true,否则返回false。

以下程序用于说明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


相关用法


注:本文由纯净天空筛选整理自Code_r大神的英文原创作品 Stack equals() method in Java with Example。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。