Sobes.tech
Junior — Middle

Can you explain what is meant by a hash function and how it works?

sobes.tech AI

Answer from AI

A hash function is a function that takes input data (such as a string or object) and returns a fixed-size value — a hash code. In Java, hash functions are widely used for quick search and comparison of objects, for example, in HashMap and HashSet collections.

Main properties of a hash function:

  • Fast computation.
  • Always returns the same hash for the same input data.
  • Minimize collisions (different data with the same hash).

Example in Java:

String s = "example";
int hashCode = s.hashCode();
System.out.println(hashCode);

Here, the hashCode() method returns the integer hash of the string, which is used, for example, to determine the position of the object in a hash table.