HashMap performance when overriding hashcode method

In HashMapif I put custom objects as a key.

What happens if I redefine hashCode()and implement it to pass the value as " 1"; will there be any performance hit?

if I change the method hashCode()to return a random value using a function Math.random() what will happen to the performance?

+4
source share
5 answers

Adding Math.random () does not affect a big hit in performance, but it is a bad idea to construct hash values ​​through the random () function. Instead, you can use some good hashing function to minimize collisions and which are much faster. For reference, you can check out some links http://www.partow.net/programming/hashfunctions/

+5
source

If you mean asymptotic time complexity, then:

since it HashMapuses hashCodeto calculate which bucket to use in the hash table, if you return 1from hashCode, you actually make your HashMapperformance metric as (unsorted) LinkedList.

HashMap, equal hashCode s.

Wikipedia:

+----------------------+----------+------------+----------+--------------+
|                      |  Insert  |   Delete   |  Search  | Space Usage  |
+----------------------+----------+------------+----------+--------------+
| Unsorted linked list | O(1)*    | O(1)*      | O(n)     | O(n)         |
| Hash table           | O(1)     | O(1)       | O(1)     | O(n)         |
+----------------------+----------+------------+----------+--------------+

, , :

  • HashMap ( O(1) O(n))
  • HashMap ( )
+4

1 hashCode() HashMap. , - . Java, 9, .

, -, .

0

1 ( , ), HashMap , " ". , , O (1), O (n) .

, HashMap . , " " (, , ). , , ( -).

equals, , .

0

Returning a fixed value to hashcode () will certainly make your hash table slower. All values ​​will be assigned to the same box, so search operations will take linear time (instead of average constant time with a decent hash function).

Returning a random value will completely terminate the hashmap contract. Values ​​will be assigned to random cells and viewed in random cells, so there is no guarantee that you will find previously stored values.

0
source

Source: https://habr.com/ru/post/1535571/


All Articles