Skip to content

Instantly share code, notes, and snippets.

@lucifercr07
Last active October 18, 2019 21:12
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 lucifercr07/b0e1adbaed2de5fdff7b7494ad6ae7e2 to your computer and use it in GitHub Desktop.
Save lucifercr07/b0e1adbaed2de5fdff7b7494ad6ae7e2 to your computer and use it in GitHub Desktop.
hashCode() and equals() method override example
package problems.DataStructuresImpl;
import java.util.Objects;
class HashCodeExample {
private String string;
private int id;
public HashCodeExample(String string, int id) {
this.string = string;
this.id = id;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
HashCodeExample that = (HashCodeExample) o;
return id == that.id && Objects.equals(string, that.string);
}
@Override
public int hashCode() {
return Objects.hash(string, id);
}
}
//Test class
class Test
{
public static void main (String[] args)
{
//Objects of HashCodeExample class.
HashCodeExample example1 = new HashCodeExample("abc123", 1);
HashCodeExample example2 = new HashCodeExample("abc123", 1);
// comparing Objects hashCode
if (example1.hashCode() != example2.hashCode()) {
System.out.println("Both Objects are not equal.");
return;
}
// Now, hashCode's are equal let's compare the objects itself
if (!example1.equals(example2)) {
System.out.println("Both Objects are not equal.");
return;
}
System.out.println("Both Objects are equal.");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment