简体   繁体   English

映射与键值相同的对象

[英]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: 在Map上Foo1和Foo2在技术上可以相等,但是您仍然希望它们对它们具有不同的品质,这在技术上是不好的设计:

  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. 我注意到在Multiset中没有有意义的get函数,因为如果set包含对象,那么您已经有了它,因此无需检索它。

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 但是同时,拥有包含相同对象的键和值的映射似乎太过致命了,这就是为什么我一直在研究Multiset的原因

Edit: combine returns the same object that still "equals" but combines attributes. 编辑:合并返回仍“等于”但合并属性的同一对象。

IE IE浏览器

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

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. 然后,您的对象可以实现此目的,并且您可以具有用于合并在自己的界面中实现的那些对象的自定义逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM