简体   繁体   English

可以在Hashmap java中将Collection用作键吗?

[英]Can Collection be used as an key in Hashmap java?

I have following scenario (modified one than actual business purpose). 我有以下情况(比实际业务目的修改了一种)。

  1. I have a program which predicts how much calories a person will loose for the next 13 weeks based on certain attributes. 我有一个程序可以根据某些属性来预测一个人在接下来的13周内会散失多少卡路里。
  2. I want to cache this result in the database so that i don't call the prediction again for the same combination. 我想将此结果缓存在数据库中,这样我就不会再为相同的组合调用预测了。
  3. I have class person class Person { int personId; String weekStartDate; } 我有班级人员class Person { int personId; String weekStartDate; } class Person { int personId; String weekStartDate; }
  4. I have HashMap<List<Person>, Integer> - The key is 13 weeks data of a person and the value is the prediction 我有HashMap<List<Person>, Integer> -关键是一个人的13周数据,值是预测
  5. I will keep the hashvalue in the database for caching purpose 我将哈希值保留在数据库中以进行缓存

Is there a better way to handle above scenario? 有没有更好的方法来处理上述情况? Any design pattern to support such scenarios 任何支持这种情况的设计模式

Depends: the implementation of hashCode() uses the elements of your list. 取决于: hashCode()的实现使用列表中的元素 So adding elements later on changes the result of that operation: 因此,稍后添加元素会更改该操作的结果:

public int hashCode() {
    int hashCode = 1;
    for (E e : this)
        hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());
    return hashCode;
}

Maps aren't build for keys that can change their hash values! 映射不是针对可更改其哈希值的键构建的! And of course, it doesn't really make sense to implement that method differently. 当然,以不同的方式实现该方法实际上没有任何意义。

So: it can work when your lists are all immutable , meaning that neither the list nor any of its members is modified after the list was used as key. 因此:当列表都是不可变的时 ,它可以工作,这意味着将列表用作键之后 ,列表及其任何成员都不会被修改。 But there is a certain risk: if you forget about that contract later on, and these lists see modifications, then you will run into interesting issues. 但是存在一定的风险:如果以后忘记该合同 ,并且这些列表中有修改,那么您将遇到一些有趣的问题。

This works because the hashcode of the standard List implementations is computed with the hashcodes of the contents. 之所以可行,是因为标准List实现的哈希码是使用内容的哈希码来计算的。 You need to make sure, however, to also implement hashCode and equals in the Person class, otherwise you will get the same problem this guy had . 但是,您需要确保在Person类中也实现hashCodeequals ,否则您将遇到这个家伙遇到的相同问题。 See also my answer on that question. 另请参阅我对该问题的回答。

I would suggest you define a class (say Data ) and use it as a key in your hashmap. 我建议您定义一个类(例如Data )并将其用作哈希图中的键。 Override equals/hashcode accordingly with knowledge of data over weeks. 因此,根据数周的数据equals/hashcode

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

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