I have a requirement where I need to fetch data from database Once I fetch it I also need to insert it into a map(a hashmap) for later retrieval. For a query on only one filter let's say "id" this approach is alright. I can easily fetch data filtered on "id" and then store it into hashmap where key value pair is <id,data>.
But now I have a requirement wherein i need to fetch data using id and access code. Then I also need to insert it into a hashmap for faster retrieval next time. Something like <(id,access code), data>. How do I do this? Which data structure would help me do this? I hope i have made my requirement clear enough.
If you end up using a custom key class, be sure to override its "equals" method (so that it returns "true" if key and access code are the same) and also the "hashCode" method. Otherwise you may see strange behavior.
Overriding equals method should not be a problem I guess. I would just need to compare the values of id and accessCode which are of Strings datatype. But what would be the best way to override hashcode since both my operands are Strings(id and accessCode)
If I introduce another field named hashCode, how do I make sure that this value is being used(as key)for retrieval of data from hashmap during call to map.get(key).
If I introduce another field named hashCode, how do I make sure that this value is being used(as key)for retrieval of data from hashmap during call to map.get(key).
Just to be picky, but hashCode is not the key. The object instance of the Key class (or whatever you end up naming it) is the key.
You'd write the hashCode method like
That's it.
Die Fledermaus does not fear such a tiny ad:
Gift giving made easy with the permaculture playing cards