📜  用示例在Java中设置 equals() 方法

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

用示例在Java中设置 equals() 方法

Java.util.Set类的equals()方法用于验证 Object 与 Set 的相等性并进行比较。如果两个集合的大小相等并且都包含相同的元素,则该方法返回 true。

句法:

public boolean equals(Object o)

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

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

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

示例 1:

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

示例 2:

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

参考:https: Java Java.lang.Object)