Search code examples
javacollectionsmultimap

Removing from multiMap


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);

}

Solution

  • you remove returns false because you are trying to remove Person object, but you don't have it in the map. Notice you are adding Collection<Person> to map, but trying to remove Person, obviously those 2 objects are not equal, therefore you get false value.

    after : map.put(1, set); in memory you have something like : 1=>[[p]]; but ,i guess, you expected 1=>[p].

    just replace map.put(1,set); with map.put(1,p);

    Also take a look at Guillaume Poussel answer for proper MultiMap implementation advice.