Let's override the difference between == (identity) and equals method (equivalence)

There are two "same" in java.

== (identity)

The == operator determines that they are the same. That is, it is determined that a plurality of variables refer to the same instance.


A a = new A(); //Create an instance called type A
A b = a; //Copy each instance of a to b as it is
System.out.println(a == b); 
true

example


public class Sample {
	private int num;
	public Sample(int num) {
		this.num = num;
	}
}
public class Main {
	public static void main(String[] args) {
		Sample s0 = new Sample(5); //Sample type instantiation
		Sample s1 = s0; //Copy to s1
		s0 = new Sample(5); //Create a new Sample type instance
		System.out.println(s0 == s1);
	}
}
false

At the time of copying with Sample s1 = s0;, it had the same instance, but on the next line, s0 created a new instance, and s0 and s1 became different instances.

equals method (equivalence)

The equals method determines that they are equivalent. That is, the instances are different, but it is determined whether they have the same value.

The equals method defined in the default Object class is

public boolean equals(Object obj){
  return (this == obj);
}

Because it is defined as, and it is a specification to confirm the identity

*** It is assumed to be used by overriding. *** ***

further! !!

*** When overriding the equals method, you must also override the hashCode in the set. *** ***

Object(Java SE 11 & JDK 11)

equals Keep in mind that in general, when overriding this method, you should always override the hashCode method and follow the general convention of the hashCode method that equivalent objects must hold the equivalent hash code.

example


public class Sample {
	private int num;
	private String name;
	public Sample(int num, String name) {
		this.num = num;
		this.name = name;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		result = prime * result + num;
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Sample other = (Sample) obj;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		if (num != other.num)
			return false;
		return true;
	}


}


public class Main {
	public static void main(String[] args) {
        //argument(num, name)Is the same
		Sample a = new Sample(5, "xxx"); 
		Sample b = new Sample(5, "xxx");
		System.out.println(a.equals(b));
        //Output each hashCode
        System.out.println(a.hashCode());
        System.out.println(b.hashCode());
	}
}
true
3694926
3694926

Overriding the equals and hashCode methods.

If even one num or name is different, it will be as follows.


public class Main {
	public static void main(String[] args) {
        //argument(name)Is different
		Sample a = new Sample(5, "xxx");
		Sample b = new Sample(5, "yyy"); 
		System.out.println(a.equals(b));
        //Output each hashCode
        System.out.println(a.hashCode());
        System.out.println(b.hashCode());
	}
}
false
3694926
3725709

The equals judgment is false, and a different value is output for hashCode.

Recommended Posts

Let's override the difference between == (identity) and equals method (equivalence)
Difference between == operator and equals method
[Java] Difference between == and equals
Difference between instance method and class method
Difference between == operator and eqals method
Understand the difference between each_with_index and each.with_index
What is the difference between an action and an instance method?
Now in the third year, the misunderstanding that I noticed is the difference between the equals method and ==
Easy to understand the difference between Ruby instance method and class method.
About the difference between irb and pry
[Rails] I studied the difference between new method, save method, build method and create method.
[Java] Understand the difference between List and Set
[iOS] Understand the difference between frame and bounds
[Rails / ActiveRecord] About the difference between create and create!
Understand the difference between abstract classes and interfaces!
What is the difference between SimpleDateFormat and DateTimeFormatter? ??
[Rails] Difference between create method and new + save method
Let's explain the difference between an interpreter and a compiler using a Venn diagram
[Ruby] What is the slice method? Let's solve the example and understand the difference from slice!
Difference between vh and%
Difference between i ++ and ++ i
[Ruby] I thought about the difference between each_with_index and each.with_index
[Rails] I learned about the difference between resources and resources
What is the difference between a class and a struct? ?? ??
What is the difference between System Spec and Feature Spec?
Ethereum Transaction Sending Method Difference between send and sendAsync
About the difference between classes and instances in Ruby
[Rails] What is the difference between redirect and render?
Compare the difference between dockerfile before and after docker-slim
[JAVA] What is the difference between interface and abstract? ?? ??
What is the difference between skip and pending? [RSpec]
[Rails] I investigated the difference between redirect_to and render.
What is the difference between Java EE and Jakarta EE?
[Swift] UITextField taught me the difference between nil and ""
[Java] Note about the difference between equivalence judgment and equality judgment when comparing String classes
Difference between product and variant
Difference between redirect_to and render
[Rails] What is the difference between bundle install and bundle update?
Rails: Difference between resources and resources
Difference between Java and JavaScript (how to find the average)
Difference between puts and print
Difference between redirect_to and render
Difference between CUI and GUI
Difference between variables and instance variables
Difference between mockito-core and mockito-all
[Ruby] About the difference between 2 dots and 3 dots of range object.
Difference between class and instance
Difference between bundle and bundle install
[Java] Check the difference between orElse and orElseGet with IntStream
Difference between ArrayList and LinkedList
Difference between render and redirect_to
Difference between List and ArrayList
Difference between .bashrc and .bash_profile
Difference between StringBuilder and StringBuffer
Difference between render and redirect_to
The difference between programming with Ruby classes and programming without it
Difference between render and redirect_to
[Ruby] Difference between each method and for statement. The elements are taken out one by one and processed.
Consider implementing a method that returns the difference between two Lists
About the difference between gets and gets.chomp (other than line breaks)
[Ruby] Difference between symbol variables and character string variables. About the difference between [: a] and ['a'].