📜  Java中的 HashSet equals() 方法与示例

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

Java中的 HashSet equals() 方法与示例

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

句法:

public boolean equals(Object o)

参数:此方法将对象 o作为参数,以便与此集合进行比较是否相等。

返回值:如果指定的对象等于此集合,则此方法返回true

下面是说明equals()方法的示例。

示例 1:

// Java program to demonstrate equals()
// method of HashSet
  
import java.util.*;
  
public class GFG {
    public static void main(String[] argv)
    {
  
        // Creating object of HashSet
        HashSet
            arrset1 = new HashSet();
  
        // Populating arrset1
        arrset1.add("A");
        arrset1.add("B");
        arrset1.add("C");
        arrset1.add("D");
        arrset1.add("E");
  
        // print arrset1
        System.out.println("First HashSet: "
                           + arrset1);
  
        // Creating another object of HashSet
        HashSet
            arrset2 = new HashSet();
  
        // Populating arrset2
        arrset2.add("A");
        arrset2.add("B");
        arrset2.add("C");
        arrset2.add("D");
        arrset2.add("E");
  
        // print arrset2
        System.out.println("Second HashSet: "
                           + arrset2);
  
        // comparing first HashSet to another
        // using equals() method
        boolean value
            = arrset1.equals(arrset2);
  
        // print the value
        System.out.println("Are both set equal: "
                           + value);
    }
}
输出:
First HashSet: [A, B, C, D, E]
Second HashSet: [A, B, C, D, E]
Are both set equal: true

示例 2:

// Java program to demonstrate equals()
// method of HashSet
  
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv)
    {
  
        // Creating object of HashSet
        HashSet
            arrset1 = new HashSet();
  
        // Populating arrset1
        arrset1.add(10);
        arrset1.add(20);
        arrset1.add(30);
        arrset1.add(40);
        arrset1.add(50);
  
        // print arrset1
        System.out.println("First HashSet: "
                           + arrset1);
  
        // Creating another object of HashSet
        HashSet
            arrset2 = new HashSet();
  
        // Populating arrset2
        arrset2.add(10);
        arrset2.add(20);
        arrset2.add(30);
  
        // print arrset2
        System.out.println("Second HashSet: "
                           + arrset2);
  
        // comparing first HashSet to another
        // using equals() method
        boolean value = arrset1.equals(arrset2);
  
        // print the value
        System.out.println("Are both set equal: "
                           + value);
    }
}
输出:
First HashSet: [50, 20, 40, 10, 30]
Second HashSet: [20, 10, 30]
Are both set equal: false