java - What role does hashCode play when comparing two objects? -


i've decided study primary documentation in java. i've started object class , looking @ equals method. know equals using hashcode method. although, hashcode returns int there limited number of unique hashcodes can generated.

what happen when try compare 2 diffrent objects have same hashcode? posible?

yes. 2 objects can have same hashcode. however, hashcode plays no role when comparing 2 objects. if want check if 2 objects of class equal, override equals , define when 2 objects of class should considered equal. if want compare if 1 object of class less than/greater other (usually while sorting collection), implement comparable , override compareto method. (you can implement comparator)

if ever want store object in hashset or use key in hashmap, make sure override hashcode method or objects hashset or keys in hashmap stored in single bucket. don't forget override equals in classes create. if don't this, 2 references object of class equal if refer same object.

you can read more equals , hashcode methods in equals , hashcode documentation.


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -