Deep and Shallow comparison

Deep and Shallow comparison

Yeah, its comparison :) I agree you must have heard deep copy or shallow copy.
Usually “deep” and “shallow” are used to refer to copying, not comparison but here I would like to give a brief difference between deep comparison and shallow comaparison of objects.
Shallow Comparison
When you do == you are comparing the references for equality. You are checking, is the address in memory the same for both Objects?

Deep comparison
When you do .equals() you are comparing the Objects themselves for equality. You are checking, do these two Objects consider themselves equal?

Here is a short example how you will write an equals method having deep comparison and shallow comparison

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package com.syed.rizvi.test;
 
public class Employee {
 
private int empid;
private String name;
public int getEmpid() {
return empid;
}
public void setEmpid(int empid) {
this.empid = empid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
 
public boolean equals(Object obj)
{
if (obj == null)
return false;
// shallow comparison
if (this == obj)
return true;
 
if (!(obj instanceof Employee))
return false;
 
Employee other = (Employee) obj;
// Deep comparison
if (this.getEmpid() == other.getEmpid() && this.getName().equals(other.getName()))
{
return true;
}
return false;
}
}

One Response to “Deep and Shallow comparison”

  1. Xohaib Nauman Says:

    alaw (y)

Leave a Reply

Spam Protection by WP-SpamFree

Einfobuzz Site Map