📌  相关文章
📜  Java中的 AbstractSet equals() 方法及示例

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

Java中的 AbstractSet equals() 方法及示例

Java AbstractSet中的AbstractSet.equals()方法用于检查两个集合之间的相等性。它验证作为参数传递的一个集合的元素是否等于该集合的元素。

句法:

AbstractSet1.equals(AbstractSet2)

参数:该方法接受一个抽象集类型的参数AbstractSet2 ,并引用与该抽象集进行相等性检查的集合。

返回值:如果相等性对两个对象集都成立,则该方法返回 true,否则返回 false。

下面的程序说明了 AbstractSet.equals() 方法的工作:

方案一:

// Java code to illustrate the equals() method
import java.util.*;
  
public class Abstract_Set_Demo {
    public static void main(String[] args)
    {
  
        // Creating an empty AbstractSet
        AbstractSet
            abstract_set1 = new HashSet();
        AbstractSet
            abstract_set2 = new HashSet();
  
        // Adding elements to set
        abstract_set1.add("Geeks");
        abstract_set1.add("4");
        abstract_set1.add("Geeks");
        abstract_set1.add("Welcomes");
        abstract_set1.add("You");
  
        // Adding elements to set
        abstract_set2.add("Geeks");
        abstract_set2.add("4");
        abstract_set2.add("Geeks");
        abstract_set2.add("Welcomes");
        abstract_set2.add("You");
  
        // Displaying the first HashSet
        System.out.println("First Set: "
                           + abstract_set1);
  
        // Displaying the second HashSet
        System.out.println("Second Set: "
                           + abstract_set2);
  
        // Displaying the equality
        System.out.println("Equality: "
                           + abstract_set1
                                 .equals(abstract_set2));
    }
}
输出:
First Set: [4, Geeks, You, Welcomes]
Second Set: [4, Geeks, You, Welcomes]
Equality: true

方案二:

// Java code to illustrate the equals() method
import java.util.*;
  
public class Abstract_Set_Demo {
    public static void main(String[] args)
    {
  
        // Creating an empty AbstractSet
        AbstractSet
            abstract_set1 = new HashSet();
        AbstractSet
            abstract_set2 = new HashSet();
  
        // Adding elements to set
        abstract_set1.add("Geeks");
        abstract_set1.add("4");
        abstract_set1.add("Geeks");
        abstract_set1.add("Welcomes");
        abstract_set1.add("You");
  
        // Adding elements to set
        abstract_set2.add("Geeks");
        abstract_set2.add("4");
        abstract_set2.add("Geeks");
        abstract_set2.add("Welcomes");
        abstract_set2.add("U");
  
        // Displaying the first HashSet
        System.out.println("First Set: "
                           + abstract_set1);
  
        // Displaying the second HashSet
        System.out.println("Second Set: "
                           + abstract_set2);
  
        // Displaying the equality
        System.out.println("Equality: "
                           + abstract_set1
                                 .equals(abstract_set2));
    }
}
输出:
First Set: [4, Geeks, You, Welcomes]
Second Set: [4, U, Geeks, Welcomes]
Equality: false