📜  用示例映射Java中的 equals() 方法

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

用示例映射Java中的 equals() 方法

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

句法:

boolean equals(object obj)

参数:该方法接受一个此映射类型的参数obj ,并引用要与此映射检查其相等性的映射。

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

下面的程序说明了Java.util.Map.equals() 方法:
方案一:

// Java code to illustrate the equals() method
import java.util.*;
  
public class Map_Demo {
    public static void main(String[] args)
    {
        // Creating an empty Map
        Map map1 = new HashMap();
        Map map2 = new HashMap();
  
        // Mapping string values to int keys
        map1.put(10, "Geeks");
        map1.put(15, "4");
        map1.put(20, "Geeks");
        map1.put(25, "Welcomes");
        map1.put(30, "You");
  
        // Mapping string values to int keys
        map2.put(10, "Geeks");
        map2.put(15, "4");
        map2.put(20, "Geeks");
        map2.put(25, "Welcomes");
        map2.put(30, "You");
  
        // Displaying the Map1
        System.out.println("First Map: "
                           + map1);
  
        // Displaying the Map2
        System.out.println("Second Map: "
                           + map2);
  
        // Checking the equality
        System.out.println("Equality: " + map1.equals(map2));
    }
}
输出:
First Map: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}
Second Map: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}
Equality: true

方案二:

// Java code to illustrate the equals() method
import java.util.*;
  
public class Map_Demo {
    public static void main(String[] args)
    {
        // Creating an empty Map
        Map map1 = new HashMap();
        Map map2 = new HashMap();
  
        // Mapping string values to int keys for map1
        map1.put(10, "Geeks");
        map1.put(15, "four");
        map1.put(20, "Geeks");
        map1.put(25, "Welcomes");
        map1.put(30, "You");
  
        // Mapping string values to int keys for map2
        map2.put(10, "Geeks");
        map2.put(15, "4");
        map2.put(20, "Geeks");
        map2.put(25, "Welcomes");
        map2.put(30, "You");
  
        // Displaying the map 1
        System.out.println("First Map: " + map1);
  
        // Displaying the map 2
        System.out.println("Second Map: " + map2);
  
        // Displaying the equality
        System.out.println("Equality: " + map1.equals(map2));
    }
}
输出:
First Map: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=four}
Second Map: {20=Geek, 25=Welcomes, 10=Geeks, 30=You, 15=4}
Equality: false

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