public static void iterateOverHashmapGeneric(){ HashMap<String, Integer> hm1 = new HashMap<String, Integer>(); hm1.put("E", 69); hm1.put("A", 65); hm1.put("G", 71); hm1.put("C", 67); Set<String> mySet = hm1.keySet(); System.out.print("foreach printing: "); for(String str : mySet) { System.out.print(str + ":" + hm1.get(str) + ", "); } HashMap<String, Integer> hm2 = new HashMap<String, Integer>(); hm2.putAll(hm1); if(hm1.equals(hm2)) { System.out.println("\n\nhm1 and hm2 contain the same elements"); } HashMap<String, Integer> hm3 = (HashMap) hm1.clone(); System.out.println("\nElements of hm3: " + hm3); }
A generics HashMap object hm1 is created that stores keys as strings and values as integers. With put() method elements are added.
Set<String> mySet = hm1.keySet(); for(String str : mySet) { System.out.print(str + ":" + hm1.get(str) + ", "); }
HashMap<String, Integer> hm2 = new HashMap<String, Integer>(); hm2.putAll(hm1); if(hm1.equals(hm2)) { System.out.println("\n\nhm1 and hm2 contain the same elements"); }
HashMap<String, Integer> hm3 = (HashMap) hm1.clone(); System.out.println("\nElements of hm3: " + hm3);
No comments:
Post a Comment