Brandon Ling
Brandon Ling

Reputation: 3919

Map with same object as key value

Is it technically bad design to have a Map where Foo1 and Foo2 could technically be equal but you still want them to have different qualities about them such that:

  Foo foo2 = new Foo("id1", 4);
    Foo foo1 = map.get(foo2);
    if(foo1 != null){
        map.replace(foo1, foo1.combine(foo2));
    }

Doesn't this technically violate "Equals"? I noticed in Multiset there is no get function which makes sense because if the set contains the object, you already have it, so no need to retrieve it.

But at the same time, it seems like over kill to have a map that contains the key and value as same object which is why I was looking into Multiset

Edit: combine returns the same object that still "equals" but combines attributes.

I.E.

public class Foo {
String id;
int length;

public combine(Foo foo){
   this.length += foo.length;
   return this;
}

@Override equals(Object o){
...
return this.id == that.id;
}

Upvotes: 0

Views: 907

Answers (1)

pandaadb
pandaadb

Reputation: 6466

Equals and hashcode have a contract that other classes rely on to be correctly implemented. I would not abuse those methods to solve this.

Better solution is to have a custom interface

public interface MergeAble<T> {

   public boolean canMerge(T other);

}

Your object can then implement this and you can have custom logic for merging for those objects implemented in your own interface.

Upvotes: 1

Related Questions