M
M
Mimocodil2022-01-11 05:24:40
Java
Mimocodil, 2022-01-11 05:24:40

What does the number 31 mean in the hashCode function definition?

I often see it in code.

Example 1 : PersonInfo from fastjson

link: https://github.com/alibaba/fastjson/blob/14a95cc5b...
public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((department == null) ? 0 : department.hashCode());
        result = prime * result + ((fax == null) ? 0 : fax.hashCode());
        result = prime * result + (female ? 1231 : 1237);
        result = prime * result + ((fullAddress == null) ? 0 : fullAddress.hashCode());
        result = prime * result + ((homepageUrl == null) ? 0 : homepageUrl.hashCode());
        result = prime * result + ((jobTitle == null) ? 0 : jobTitle.hashCode());
        result = prime * result + (male ? 1231 : 1237);
        result = prime * result + ((mobileNo == null) ? 0 : mobileNo.hashCode());
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        result = prime * result + ((phones == null) ? 0 : phones.hashCode());
        return result;
    }

Example 1 : RecordsTest from moshi

Link: https://github.com/square/moshi/blob/5cf5f9664cd34...
public int hashCode() {
      int result =
          Objects.hash(
              firstName,
              lastName,
              age,
              nationalities,
              weight,
              tattoos,
              hasChildren,
              superWildcard,
              extendsWildcard,
              unboundedWildcard,
              objectList,
              foodPreferences,
              setListMapArrayInt);
      result = 31 * result + Arrays.hashCode(favoriteThreeNumbers);
      result = 31 * result + Arrays.hashCode(favoriteArrayValues);
      result = 31 * result + Arrays.hashCode(nestedArray);
      return result;
    }
  }


Sometimes other numbers are put instead of 31. For example, in the libgdx library ( https://github.com/libgdx/libgdx ) almost always put different numbers
Examples: https://github.com/libgdx/libgdx/search?p=1&q=publ...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
ambisinister One, 2022-01-14
@ambisinistrone

61e13cff49815610728548.png

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question