Skip to content

Instantly share code, notes, and snippets.

@adohe-zz
Created July 17, 2014 02:38
Show Gist options
  • Select an option

  • Save adohe-zz/68dd1cbe5fe064025f5b to your computer and use it in GitHub Desktop.

Select an option

Save adohe-zz/68dd1cbe5fe064025f5b to your computer and use it in GitHub Desktop.
equals() and hashCode() contract in Java
package com.westudio.java;
import java.util.HashMap;
import java.util.Map;
class Apple {
public String color;
public Apple(String color) {
this.color = color;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Apple)) {
return false;
}
if (obj == this) {
return true;
}
return ((Apple) obj).color.equals(this.color);
}
@Override
public int hashCode() {
return this.color.length();
}
}
public class EqHash {
public static void main(String[] args) {
Map<Apple, Integer> map = new HashMap<Apple, Integer>();
map.put(new Apple("green"), 20);
map.put(new Apple("red"), 30);
// If not override the hashCode method this will get null
System.out.println(map.get(new Apple("green")));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment