简体   繁体   English

HashMap复合键-停止在每个调用解决方案中创建键对象

[英]HashMap composite key - stop creating key objects each call solution

When defining a composite key for a hash map such as: 为哈希映射定义组合键时,例如:

public key {
   enum a;
   enum b;
   enum c;

} }

Where equals and hashcode are overridden to compare these values (a,b,c)? 在哪里等于和哈希码被覆盖以比较这些值(a,b,c)?

Are there techniques to store this list of keys so they can be found by querying the three values rather than creating the new key each time? 是否存在存储此键列表的技术,以便可以通过查询三个值而不是每次都创建新键来找到它们? Such as store list of keys? 如商店清单的钥匙? Or try and reuse a key? 还是尝试重用密钥?

Garbage collection will be large as these keys will be generated on each method calls. 由于这些密钥将在每次方法调用时生成,因此垃圾收集将很大。

So we can stop: 所以我们可以停止:

public void update(obj) {

   Key = new Key(obj.a, obj.b, obj.c)
   // assume already in there map or add
   Val val = hashmap.get(key) 
   val.update(obj.newvalues) // do some calculation

   return val;
   // key will then be lost after get? So lots of Garbage collection? 
   // if so should it explicitly be set to key = null; 
}

There is no easy way to do this as you expected. 没有如您所愿的简单方法。 It might be needed to create a Map that takes three keys. 可能需要创建一个包含三个键的Map。

If it is a concern for the program to generate a new Key instance just for query, consider using Integer as key HashMap. 如果程序担心仅生成新的Key实例以供查询,请考虑使用Integer作为键HashMap。 But keep in mind Integer is also an instance. 但是请记住,Integer也是一个实例。 It could be faster for HashMap to compare and get the value. HashMap进行比较并获取值可能更快。 It might uses less memory than the self-defined key instance. 它可能比自定义键实例使用更少的内存。 But not helping to avoid "key" instance to be created (Unless the Integer instance is cached by JVM which is another story.). 但是,这有助于避免创建“关键”实例(除非另外一个情况是JVM缓存了Integer实例)。

About using Integer as key: 关于使用整数作为键:

If the Key is three enum, try to use Integer as key and do a math translation, making sure different combine of three enums can get a different integer value. 如果Key是三个枚举,请尝试使用Integer作为键并进行数学转换,确保三个枚举的不同组合可以获得不同的整数值。

For example, suppose there are 16 values for enum a,enum b and enum c. 例如,假设枚举a,枚举b和枚举c有16个值。 It is doable to use java bye operator to get a integer to represent the combine. 可以使用java bye运算符来获取表示合并的整数。 Then use the Integer to get value from map. 然后使用Integer从地图中获取价值。

Hope this helps. 希望这可以帮助。

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

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