检查 Java 中的两个 HashMap 是否相等
如需检查两个 HashMap 是否相等,请使用 equals() 方法。
我们首先创建第一个 HashMap -
// Create hash map 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("Air Purifiers", new Integer(300)); hm1.put("Food Processors", 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("Air Purifiers", new Integer(300)); hm2.put("Food Processors", new Integer(950));
如需检查两个 HashMap 是否相等,请像这样使用 equals() 方法 -
hm1.equals(hm2)
以下是一个示例,用于检查两个 HashMap 是否相等 -
示例
import java.util.*; public class Demo { public static void main(String args[]) { // Create hash map 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("Air Purifiers", new Integer(300)); hm1.put("Food Processors", new Integer(950)); System.out.println("Map 1 = "+hm1); // Create hash map 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("Air Purifiers", new Integer(300)); hm2.put("Food Processors", 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, Food Processors=950, Air Purifiers=300, Jeans=1200, Android TV=450, Trousers=600} Map 2 = {Shirts=700, Food Processors=950, Air Purifiers=300, Jeans=1200, Android TV=450, Trousers=600} Map 1 is equal to Map 2? true
广告