why it’s prefered to use Strings and wrapper that represents a specific object in hash tables rather than using the actual object itself?
why it’s prefered to use Strings and wrapper that represents a specific object in
Share
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.
The question is a bit vague, but maybe this helps:
The key must be immutable. String (Integer, Long) fits this nicely. (Of course this does not help if you later change the object to no longer match the key).
The key must implement the hashCode/equals contract. String (Integer, Long) already does this.
You can lookup by key without having to create an instance of your custom object.
So, if you are keying on a property or computed value for a custom object, it is convenient (and safe) to use a “primitive” built-in class to represent that derived value.
In fact, it is rarely necessary or advisable to use a custom class for hashtable keys, you can cover almost everything with Strings, Integers and Longs (frequent exception: tuples, for which Java has no good built-in class, and arrays don’t work as hash keys).