I want to implement a HashMap with a key with 2 components. Ex.
Pseudocode: Key = <Component1, Component2> CollName<Key, Val> coll = new CollName<Key, Val>;
How can I implement this in Java, considering speed and size of the Collection. Thanks 😀
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You need a helper (composite key) class that holds your two keys
and then you can use it as key:
It is very important here to implement
equals()andhashCode()in a good fashion. Most IDEs can help you here. Important is for the hashCode that it returns a “unique” value in order to prevent hash collisions of the keys (i.e. returning a constant value is the worst case, as all values would end up in the same bucket). Many implementations of hashcode do something alongIf you want more details, dig out any CS book that talks about hashing algorithms.
If you want to use that for persistence, also have a look at this blog post.