当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java EnumMap equals()用法及代码示例


Java中的Java.util.EnumMap.equals(obj)用于比较传递的对象与此EnumMap的相等性。必须记住,传递的对象必须是与EnumMap相同类型的映射。

用法:

boolean equals(Object obj)

参数:该方法采用Object类型的一个参数obj,表示要与此Map进行比较的Map。


返回值:如果指定对象等于Map,则该方法返回true,否则返回false。

以下示例程序旨在说明equals()方法的用法方式:

示例1:

// Java program to demonsrate equals() method 
import java.util.*; 
  
// An enum of gfg ranking worldwide and in India 
public enum gfg { 
    Global_2018, 
    India_2018, 
    China_2018 
} 
; 
  
class Enum_map { 
    public static void main(String[] args) 
    { 
  
        EnumMap<gfg, Integer> mp1 = new EnumMap<gfg, Integer>(gfg.class); 
  
        EnumMap<gfg, Integer> mp2 = new EnumMap<gfg, Integer>(gfg.class); 
  
        // Values are associated in mp1 
        mp1.put(gfg.Global_2018, 800); 
        mp1.put(gfg.India_2018, 72); 
  
        // Values are associated in mp2 
        mp2.put(gfg.Global_2018, 800); 
        mp2.put(gfg.India_2018, 72); 
  
        // Stores the result 
        boolean res1 = mp1.equals(mp2); 
  
        // Prints the result 
        System.out.println("Map1 equal to Map2: " + res1); 
  
        mp2.put(gfg.China_2018, 1607); 
  
        // Stores the result 
        boolean res2 = mp1.equals(mp2); 
  
        // Prints the result 
        System.out.println("Map1 equal to Map2: " + res2); 
    } 
}
输出:
Map1 equal to Map2: true
Map1 equal to Map2: false

示例2:

// Java program to demonsrate equals() method 
import java.util.*; 
  
// an enum of gdp growth rate 
// in recent years of India 
public enum gdp { 
    Ind_2015, 
    Ind_2016, 
    Ind_2017, 
    Ind_2018, 
    Ind_2019 
} 
; 
  
class Enum_map { 
    public static void main(String[] args) 
    { 
  
        EnumMap<gdp, String> mp1 = new EnumMap<gdp, String>(gdp.class); 
  
        EnumMap<gdp, String> mp2 = new EnumMap<gdp, String>(gdp.class); 
  
        // Values are associated in mp1 
        mp1.put(gdp.Ind_2015, "8.4"); 
        mp1.put(gdp.Ind_2016, "9.2"); 
        mp1.put(gdp.Ind_2017, "6.1"); 
        mp1.put(gdp.Ind_2018, "7.7"); 
  
        // Values are associated in mp2 
        mp2.put(gdp.Ind_2015, "8.4"); 
        mp2.put(gdp.Ind_2016, "9.2"); 
        mp2.put(gdp.Ind_2017, "6.1"); 
        mp2.put(gdp.Ind_2018, "7.7"); 
  
        // Stores the result 
        boolean res1 = mp1.equals(mp2); 
  
        // Prints the result 
        System.out.println("Map1 equal to Map2: " + res1); 
  
        mp2.put(gdp.Ind_2019, "7.0"); 
  
        // Stores the result 
        boolean res2 = mp1.equals(mp2); 
  
        // Prints the result 
        System.out.println("Map1 equal to Map2: " + res2); 
    } 
}
输出:
Map1 equal to Map2: true
Map1 equal to Map2: false


相关用法


注:本文由纯净天空筛选整理自akash1295大神的英文原创作品 EnumMap equals() Method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。