Created
July 17, 2014 02:38
-
-
Save adohe-zz/68dd1cbe5fe064025f5b to your computer and use it in GitHub Desktop.
equals() and hashCode() contract in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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