In school we are to implement our own class MultiMap.
When I were implementing the remove method, I ran in to some trouble.
My problem is when I call the remove method, the set.Remove(value) returns false. Just like if the set didn't contain the object.
I've tried to write out the object refferences from the main, and the object reference from the MultiMap class, and the objects seems to be the same.
What am I missing here?
Thanks in advance
Here's my map code :
public class MultiMap<K, V> {
private final Map<K, Set<V>> map = new HashMap<>();
public MultiMap() {
}
public String toString() {
StringBuilder sb = new StringBuilder();
Set<K> keys = map.keySet();
for (K k : keys) {
sb.append("key ");
sb.append(k);
sb.append(" Value ");
sb.append(map.get(k));
}
return sb.toString();
}
public int size() {
return map.size();
}
public boolean put(K key, V value) {
Set<V> set;
if (map.containsKey(key)) {
set = map.get(key);
set.add(value);
} else {
set = new HashSet<>();
set.add(value);
}
return (map.put(key, set) != null) ? false : true;
}
public Set<V> get(K key) {
return map.get(key);
}
public void remove(K key, V value) {
Set<V> set = map.get(key);
System.out.println(value);
System.out.println(set.remove(value));
if(set.isEmpty()) {
map.remove(key);
}
}
Main:
public static void main(String[] args) {
Person p = new Person("navn");
Collection<Person> set = new HashSet<>();
set.add(p);
MultiMap map = new MultiMap<>();
map.put(1, set);
System.out.println(map.toString());
System.out.println(map.get(1));
map.remove(1, p);
}
The first problem is in your put() method. You shall not create a new HashSet every time you insert a new element.
You should first check whether your underlying map contains the provided key, by using containsKey(). If the key exists, just add the new value. Otherwise, create a new HashSet and keep your code.
Then, you will have to fix your remove() method. It will raise a NullPointerException if the key does not exists. Indeed, map.get(key) will return null and set.remove() will fail.
EDIT:
See @Eugen Halca answer about your Multimap usage. In your main() method, you are adding a Collection of Person, but trying to remove a single Person. Even with the best Multimap implementation, that won't work ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With