檢查 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
廣告