Reputation: 1067
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)?
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;
}
Upvotes: 0
Views: 655
Reputation: 4951
There is no easy way to do this as you expected. It might be needed to create a Map that takes three keys.
If it is a concern for the program to generate a new Key instance just for query, consider using Integer as key HashMap. But keep in mind Integer is also an instance. It could be faster for HashMap to compare and get the value. 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.).
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.
For example, suppose there are 16 values for enum a,enum b and enum c. It is doable to use java bye operator to get a integer to represent the combine. Then use the Integer to get value from map.
Hope this helps.
Upvotes: 2