|
1.hashcode is used to find, if you have learned the data structure, you should know that in the chapter of find and sort
Such as in memory
0 1 2 3 4 5 6 7
And I have a class, this class has a field called ID, I want to store this class in one of the above 8 locations, if you do n’t store it arbitrarily, then you need to go to each of these eight locations when searching , Or use algorithms such as dichotomy.
But if you use hashcode, it will improve the efficiency a lot.
There is a field in our class called ID, so we define our hashcode as ID% 8, and then store our class in the position where the remainder is obtained. For example, if our ID is 9, and the remainder of 9 divided by 8 is 1, then we store the class at position 1. If the ID is 13, and the remainder is 5, then we put the class at position 5. In this way, when searching for this class, you can directly find the storage location by dividing the ID by 8 and finding the remainder.
2. But what if the two classes have the same hashcode (we assume that the ID of the above class is not unique), for example, the remainder of 9 divided by 8 and 17 divided by 8 is 1, then this is not legal, The answer is: yes. So how to judge? At this point you need to define equals.
In other words, we first use hashcode to determine whether two classes are stored in a bucket, but there may be many classes in this bucket, then we need to find the class we want in this bucket by using equals.
Well. Overriding equals (), why should we overwrite hashCode ()?
Think about it, if you want to find something in a bucket, you must first find the bucket. You don't find the bucket by rewriting hashcode (). What's the use of rewriting equals ()?
3. There are two ways to sort Class A. One is to let Class A implement the comparabole structure and implement the compareTo () method. Then you can sort them by Collections.sort (List <A> list)
Another method: define a class B to implement the Comparator class and implement the compare method,
Then sort by Collections.sort (List <A> list, B b) |
|