[Java Core] - hashCode method
June 26, 2019 |hashCode()
A hash code is a integer number which puts instance of a class into a finite number of categories.
When you override equals(), you are also expected to override hashCode() method because the hashcode is used when storing the object as a key in a maps. the has code was used in Collection as HashMap, HashTable, HashSet.
There are 4 points when override hashMap().- When equals() was override, hashCode must be override too.
- The result of hashCode must be not change. This mean that you shoudn't include the variable usually change or not unique
- If equals() return true when called with two objects, Java program call hashCode() on each of those object must return the same result.
- If equals() return false when called with two objects, calling hashCode() on each of those object doesn't have return a different result.
Example: Not Override hashCode()
public class Card {
private String rank;
private String suit;
public Card(String r, String s) {
if (r == null || s == null) {
throw new IllegalArgumentException("arg1,arg2 are null.");
}
rank = r;
suit = s;
}
@Override
public String toString() {
return "rank:" + this.rank + " suit: " + this.suit;
}
@Override
public boolean equals(Object obj) {
if ( !(obj instanceof Card)) return false;
Card c = (Card) obj;
return rank.equals(c.rank) && suit.equals(c.suit);
}
}
public class HashCodeTest {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Card card1 = new Card("1", "1");
Card card2 = new Card("1", "1");
Set<Card> cardList = new HashSet<>();
cardList.add(card1);
cardList.add(card2);
System.out.println(cardList);
}
}
Result:
run:
[rank:1 suit: 1, rank:1 suit: 1]
BUILD SUCCESSFUL (total time: 0 seconds)
Example: Override hashCode()
Add block code to Card class
@Override
public int hashCode() {
return rank.hashCode();
}
Result:
run:
[rank:1 suit: 1]
BUILD SUCCESSFUL (total time: 0 seconds)