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

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

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

Java.util.TreeSet类的equals()方法用于比较指定对象与该集合是否相等。当且仅当指定的对象也是一个集合,两个集合具有相同的大小,并且两个集合中所有对应的元素对都相等时,才返回 true。 (如果 (e1==null ? e2==null : e1.equals(e2)) 两个元素 e1 和 e2 相等。)换句话说,如果两个集合以相同的顺序包含相同的元素,则它们被定义为相等.

句法:

public boolean equals(Object o)

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

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

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

示例 1:

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

示例 2:

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