Sometimes a box will have more than one object in it, but if you are looking for a rocket, it's still much quicker to compare a peanut and a rocket, than to check a whole pile of cabbages, peas, banjos, and rhinoceroses. What about the rhinoceros, though? It has 10 characters, so we'll change our algorithm a little and "wrap around" so that 10-letter objects go in box 1, 11 letters in box 2 and so on. So the cabbage goes in box 7, the pea goes in box 3, the rocket in box 6, the banjo in box 5 and so on. In the example, let's use a really simple way of doing this - the number of letters in the name of the object. Now imagine that you don't want to bother with the index, you want to be able to find out immediately from the object which box it lives in. you decide to find the cabbage so you look up which box the cabbage is in, then go straight to that box to get it. What you need is a way of instantly deciding which box you have put each object in. You also have a pile of wildly different objects to store in these boxes, but once they are in there you need to be able to find them as quickly as possible. you have nine boxes, each marked with a number 1 to 9. This is what allows objects to be stored/retrieved quickly in a Hashtable. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the Java programming language.)Ī hashcode is a number generated from any object. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.Īs much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. It is not required that if two objects are unequal according to the equals() method, then calling the hashCode method on each of the two objects must produce distinct integer results. If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result. This integer need not remain consistent from one execution of an application to another execution of the same application. Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This method is supported for the benefit of hashtables such as those provided by. Returns a hash code value for the object.
0 Comments
Leave a Reply. |