Hello,
I want to write a method that will give me the union of 2 maps. So far i wrote some code that compiled and gave me no error, but when i run it it gives me an error which i couldnt find why it was giving it to me.
The error : java.lang.UnsupportedOperationException: null (in java.util.AbstractCollection)
and here is my code:
Iam getting an error at the bold line positionCode:import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.Iterator;
public class Ex9
{
public static void main (String[] args)
{
Map<Integer, Integer> map1 = new HashMap<Integer, Integer> ();
map1.put(7, 1);
map1.put(18, 5);
map1.put(42, 3);
map1.put(76, 10);
map1.put(98, 2);
map1.put(234, 50);
Map<Integer, Integer> map2 = new HashMap<Integer, Integer> ();
map2.put(7, 2);
map2.put(11, 9);
map2.put(42, -12);
map2.put(98, 4);
map2.put(234, 0);
map2.put(999, 3);
System.out.println("Map 1 : " + map1);
System.out.println("Map 2 : " + map2);
Map<Integer, Integer> result = union(map1, map2);
System.out.println("The union of the above maps is : " + result);
}
/**
* Returns a new map of integer keys and values which consists on the union of 2 maps.
*
* @param map1 The first map of integer keys and values.
* @param map2 The second map of integer keys and values.
* @return A new map which is the union of both maps.
*/
public static Map<Integer, Integer> union (Map<Integer, Integer> map1, Map<Integer, Integer> map2)
{
if (map1.isEmpty())
{
return map2;
}else if (map2.isEmpty()) {
return map1;
}else{
Map<Integer, Integer> result = new HashMap<Integer, Integer> ();
Set<Integer> keys = map1.keySet();
[B]keys.addAll(map2.keySet());[/B]
Iterator<Integer> i = keys.iterator();
while (i.hasNext())
{
int key = i.next();
if (map1.containsKey(key) && map2.containsKey(key))
{
int val1 = map1.get(key);
int val2 = map2.get(key);
result.put(key, (val1 + val2));
}else if (map1.containsKey(key) && !map2.containsKey(key)){
result.put(key, map1.get(key));
}else{
result.put(key, map2.get(key));
}
}
return result;
}
}
}
Also, is this a correct way of doing the union of two maps?
Regards,
EDIT: I just tried this this line of code too but didnt work
Code:Set<Integer> keys = map1.keySet();
Set<Integer> keys2 = map2.keySet();
Iterator<Integer> i2 = keys2.iterator();
while (i2.hasNext())
{
keys.add(i2.next());
}

