Java EnumMap equals()

equals() 用于比较两个EnumMap是否相等。

1 语法

public boolean equals(Object o)  

2 参数

o:需要比较的对象

3 返回值

如果两个比较的对象相等,返回true,否则返回false。

4 EnumMap equals()示例1

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java EnumMap.equals的例子
 */
import java.util.*;

public class Demo {

    // create an enum
    public enum Tutorial {
        CSS, Python, PHP, Java, Javascript
    };
    public static void main(String[] args) {
        //创建两个EnumMap对象
        EnumMap<Tutorial, String>  map1 =
                new EnumMap<Tutorial, String> (Tutorial.class);
        EnumMap<Tutorial, String>  map2 =
                new EnumMap<Tutorial, String> (Tutorial.class);

        map1.put(Tutorial.CSS, "1");
        map1.put(Tutorial.Python, "2");
        map1.put(Tutorial.PHP, "3");
        map1.put(Tutorial.Java, "4");

        map2.put(Tutorial.CSS, "1");
        map2.put(Tutorial.Python, "2");
        map2.put(Tutorial.PHP, "3");
        map2.put(Tutorial.Java, "4");
        // 打印map1和map2
        System.out.println("Map1:"+map1);
        System.out.println("Map2:"+map2);
        // 判断两个Map是否相等
        boolean equal = map1.equals(map2);
        System.out.println("Map1 and Map 2 are equal: "+equal);
        map2.put(Tutorial.Javascript, "5");
        // 打印map1和map2
        equal = map1.equals(map2);
        System.out.println("Map1 and Map 2 are equal: "+equal);
    }
}

输出结果为:

Map1:{CSS=1, Python=2, PHP=3, Java=4}
Map2:{CSS=1, Python=2, PHP=3, Java=4}
Map1 and Map 2 are equal: true
Map1 and Map 2 are equal: false

5 EnumMap equals()示例2

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java EnumMap.equals的例子
 */
import java.util.*;

public class Demo {

    // 创建枚举
    public enum Days {
        Monday, Tuesday, Wednesday, Thursday
    };
    public static void main(String[] args) {
        //创建两个EnumMap
        EnumMap<Days, String> map1= new EnumMap<Days, String>(Days.class);
        EnumMap<Days, String> map2= new EnumMap<Days, String>(Days.class);

        map1.put(Days.Monday,"1");
        map1.put(Days.Tuesday,"2");
        map1.put(Days.Wednesday,"3");


        map2.put(Days.Monday,"1");
        map2.put(Days.Tuesday,"2");
        map2.put(Days.Wednesday,"3");

        // 打印map1和map2
        System.out.println("Map1:"+map1);
        System.out.println("Map2:"+map2);
        //判断两个Map是否相等
        boolean equal = map1.equals(map2);
        System.out.println("Map1 and Map 2 are equal: "+equal);
        map2.put(Days.Thursday,"4");
        // 打印map1和map2
        equal = map1.equals(map2);
        System.out.println("Map1 and Map 2 are equal: "+equal);
    }
}

输出结果为:

Map1:{Monday=1, Tuesday=2, Wednesday=3}
Map2:{Monday=1, Tuesday=2, Wednesday=3}
Map1 and Map 2 are equal: true
Map1 and Map 2 are equal: false

 

热门文章

优秀文章