r/javahelp • • May 20 '20

Wouldn't the Eclipse's auto generated hashcode method go above max int value way too quickly?

@Overridepublic int hashCode() {
	final int prime = 31;
	int result = 1;

	result = prime * result + a;
	result = prime * result + b;
        result = prime * result + c;
	result = prime * result + d;

	return result;
}

Say a,b,c,d are only above 100, it would already return a number way above the max integer value. Does this hash function only have very limited uses or am I missing something?

19 Upvotes

5 comments sorted by

View all comments

22

u/Doddzi24 May 20 '20

Yes, it can actually overflow multiple times.

The thing is that this doesn't really matter. Each time the hashcode method is called on a distinct object, it will overflow at the exact same point(s) every time, meaning it will still return the same hashcode every time.

4

u/ReligionIsAScam_ May 20 '20

Ah makes a lot of sense, thanks!