Skip to content

Instantly share code, notes, and snippets.

@jostly
Created January 18, 2013 10:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jostly/4563579 to your computer and use it in GitHub Desktop.
Save jostly/4563579 to your computer and use it in GitHub Desktop.
The trouble with hashCode in mutable objects
import java.util.HashSet;
import java.util.Set;
public class Main {
public static void main(String[] args) {
Set<Foo> set = new HashSet<Foo>();
Foo apple = new Foo("apple");
set.add(apple);
set.add(new Foo("apple")); // Don't add duplicate objects
System.out.print("Set is size: " + set.size() + " and contains: ");
for(Foo foo : set) {
System.out.print(foo.getValue() + " (" + foo.hashCode() + "), ");
}
System.out.println("");
apple.setValue("banana");
set.add(new Foo("banana")); // Shouldn't add a duplicate object, but ...
System.out.print("Set is size: " + set.size() + " and contains: ");
for(Foo foo : set) {
System.out.print(foo.getValue() + " (" + foo.hashCode() + "), ");
}
}
}
// POJO value class, nothing strange, autogenerated hashCode and equals
class Foo {
private String value;
public Foo(String value) {
super();
this.value = value;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((value == null) ? 0 : value.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Foo other = (Foo) obj;
if (value == null) {
if (other.value != null)
return false;
} else if (!value.equals(other.value))
return false;
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment