When I look at a Map object (HashMap or Hashtable) in the Eclipse debugger, I see that the Map object maintains an internal table into which key/value pairs have been inserted. Is there any way to obtain the table index number for a specific key value?
The reason I ask is because the application I am currently working on creates large HashMaps. To aid in debugging, I created a class that takes a Map object and prints it out in alpha order. However, I would also like to be able to display the corresponding index into the Map table if that is possible.
getFields() returns the public fields of a class and its superclasses. You want getDeclaredFields(), which lists all the fields in a given class (except the inherited ones.)
The index in that array (and indeed, the size of the array itself) can change over time as the HashMap grows and is rehashed. The index isn't really meaningful to anyone but HashMap's implementers, so I don't know why you'd want to display it.
Furthermore, the name, type, and other information about that array -- or even the existence of the array at all -- can theoretically change in each JDK version, so I wouldn't get too comfy with any solution you come up with.
But in any case, looking at the JDK 1.4.2 source, there's this:
and there's this:
It's used like this:
So what you could do would be to get the length of the table array using reflection, and then these routines will tell you the index. You could put them into your code directly, or you could use reflection to call them in HashMap. It's your call.
Thanks for the information. You're right, I don't really need to display the index. I just wanted to do so for sake of completeness (and also to be able to cross-reference the results of my class output to what I observe in the debugger).
posted 16 years ago
Thanks for your help. Here is one solution. Note that it only works for HashMaps not Hashtables.
She said she got a brazillian. I think owning people is wrong. That is how I learned ... tiny ad: