Last active
October 18, 2019 21:12
-
-
Save lucifercr07/b0e1adbaed2de5fdff7b7494ad6ae7e2 to your computer and use it in GitHub Desktop.
hashCode() and equals() method override example
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 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