The == operator is used to compare the identities of reference data types (not the contents of primitive data types).
It basically checks if the references point to the same object. Even if the actual values in those two objects are identical, it will return a false value if they are separate objects.
Using the Equals() Method
If you want to compare the contents of reference data types, then you should use the Equals() method, which is available via the Object class, although must override it in the classes you create.
For example, let’s say we would like to compare two student IDs to check if they are the same. We can use the equals() method.
Here’s a walkthrough:
Let’s say we created a studentID in the class Student:
private int studentID;
Now, we want to create a method to compare two student IDs.
To start with, you have to declare the method and pass an Object as the parameter:
public boolean equals(Object obj);
The next line will use the == operator, already discussed, to check if the objects we will be comparing are the same object in the memory. If they are, there will be no more need to continue with the code.
if (this == obj) return true;
If they are not the same object, we must check if the Object passed as a parameter is of the class Student so we can compare the IDs:
if (obj instanceof Student){
If it is, we can proceed with casting the object as a Student object, after which we can compare it:
Student a = (Student) obj;
Now we can compare the values of current student ID and that belonging to the Object typecast to a Student object “a”:
return studentID == a.studentID;
Remember to include an else block, which specifies that if the passed object was not an object of the class Student, we simply call the equals() method of the superclass:
else{
return super.equals(obj)
}
Let’s see the entire code again:
@Override
public boolean equals(Object obj){
if (this == obj) return true;
if (obj instanceof Student){
Student a == (Student) obj;
return studentID = a.studentID;
}
else{
return super.equals(obj)
}
}
_
Top comments (0)