若要检查两个HashMap是否相等,请使用equals()
方法。
让我们首先创建第一个HashMap-
//创建哈希映射1- HashMap hm1 = new HashMap(); hm1.put("Shirts", new Integer(700)); hm1.put("Trousers", new Integer(600)); hm1.put("Jeans", new Integer(1200)); hm1.put("Android TV-------", new Integer(450)); hm1.put("空气净化器", new Integer(300)); hm1.put("食品加工机", new Integer(950));
现在让我们创建第二个HashMap-
HashMap hm2 = new HashMap(); hm2.put("Shirts", new Integer(700)); hm2.put("Trousers", new Integer(600)); hm2.put("Jeans", new Integer(1200)); hm2.put("Android TV-------", new Integer(450)); hm2.put("空气净化器", new Integer(300)); hm2.put("食品加工机", new Integer(950));
要检查两个HashMap是否相等,请使用如下equals()
方法-
hm1.equals(hm2)
以下是检查两个HashMap是否相等的示例-
import java.util.*; public class Demo { public static void main(String args[]) { //创建哈希映射1- HashMap hm1 = new HashMap(); hm1.put("Shirts", new Integer(700)); hm1.put("Trousers", new Integer(600)); hm1.put("Jeans", new Integer(1200)); hm1.put("Android TV-------", new Integer(450)); hm1.put("空气净化器", new Integer(300)); hm1.put("食品加工机", new Integer(950)); System.out.println("Map 1 = "+hm1); //创建哈希映射2- HashMap hm2 = new HashMap(); hm2.put("Shirts", new Integer(700)); hm2.put("Trousers", new Integer(600)); hm2.put("Jeans", new Integer(1200)); hm2.put("Android TV-------", new Integer(450)); hm2.put("空气净化器", new Integer(300)); hm2.put("食品加工机", new Integer(950)); System.out.println("Map 2 = "+hm2); System.out.println("Map 1 is equal to Map 2? "+hm1.equals(hm2)); } }
输出结果
Map 1 = {Shirts=700, 食品加工机=950, 空气净化器=300, Jeans=1200, Android TV-------=450, Trousers=600} Map 2 = {Shirts=700, 食品加工机=950, 空气净化器=300, Jeans=1200, Android TV-------=450, Trousers=600} Map 1 is equal to Map 2? true