當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Set 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<String> arrset1 = new HashSet<String>(); 
  
        // 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<String> arrset2 = new HashSet<String>(); 
  
        // 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<Integer> arrset1 = new HashSet<Integer>(); 
  
        // 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<Integer> arrset2 = new HashSet<Integer>(); 
  
        // 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://docs.oracle.com/javase/7/docs/api/java/util/Set.html#equals(java.lang.Object)



相關用法


注:本文由純淨天空篩選整理自gopaldave大神的英文原創作品 Set equals() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。