Java Object class is the super class of all the Java classes. All Java classes implements the Object class by default. The Java Object class provides the two important methods to compare two objects in java.
Java provides the two methods of the Object class to compare the objects are as follows:
- Java equals() Method
- Java hashCode() Method
Java equals() Method
The equals() method of the Object class compare the equality of two objects. The two objects will be equal if they share the same memory address.
Java hashCode() Method
It is a unique id provided by jvm to a Java object. Each Java object is associated with the hash code. The hash code is managed by a hash-based data structure.
Remember: When we override the equals() method, it is necessary to override the hashCode() method, also.
Approach: Using equals()
Java
public class CompareTwoObject {public static void main(String[] args) {Integer num1 = 123;Long num2 = 123l;System.out.println("Compare two object using equals() " + num1.equals(num2));System.out.println("Compare two object using equals() " + num1.equals(123));System.out.println("Compare two object using equals() " + num2.equals(123));System.out.println("Compare two object using equals() " + num2.equals(123l));}}
Output:
Compare two object using equals() falseCompare two object using equals() trueCompare two object using equals() falseCompare two object using equals() true
Approach: Using hashcode()
Java
public class CompareTwoObject {public static void main(String[] args) {Person p1=new Person("Ram",25);Person p2=new Person("Ram Singh",25);Person p3=new Person("Ram",25);System.out.println("Hashbode() of p1 "+p1.hashCode());System.out.println("Hashbode() of p2 "+p2.hashCode());System.out.println("Hashbode() of p3 "+p3.hashCode());System.out.println("Compare the p1 and p2 "+p1.equals(p2));System.out.println("Compare the p1 and p3 "+p1.equals(p3));}}class Person {private String name;private int age;public Person(String name, int age) {super();this.name = name;this.age = age;}@Overridepublic int hashCode() {final int prime = 31;int result = 1;result = prime * result + age;result = prime * result + ((name == null) ? 0 : name.hashCode());return result;}@Overridepublic boolean equals(Object obj) {if (this == obj)return true;if (obj == null)return false;if (getClass() != obj.getClass())return false;Person other = (Person) obj;if (age != other.age)return false;if (name == null) {if (other.name != null)return false;} else if (!name.equals(other.name))return false;return true;}}
Output:
Hashbode() of p1 83654Hashbode() of p2 -1683822657Hashbode() of p3 83654Compare the p1 and p2 falseCompare the p1 and p3 true
No comments:
Post a Comment