This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Beginning Java and the fly likes Deep and Shallow Comparison!! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Deep and Shallow Comparison!!" Watch "Deep and Shallow Comparison!!" New topic
Author

Deep and Shallow Comparison!!

Ravi Kumar Ravuru
Ranch Hand

Joined: Apr 18, 2002
Posts: 176
Hello Folks,
What is difference between deep and shallow comparison?Which of the two comparisons are used in equals() method of Object?Please help me out.
Regards,
Ravi
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

Usually "deep" and "shallow" are used to refer to copying, not comparison. But by analogy, "deep" comparison would mean comparing two objects, and all the objects they reference as members, and all the objects they reference, etc. "Shallow" comparison, in contrast, would mean just comparing two objects, I suppose.
Object.equals() does a "shallow" comparison, I suppose, but this is only because Object has no data members. Most implementations of equals() should do "deep" comparisons.


[Jess in Action][AskingGoodQuestions]
Jason Menard
Sheriff

Joined: Nov 09, 2000
Posts: 6450
Like Ernest said, the reference is usually to "deep" and "shallow" copies.
A shallow copy of an ArrayList would make a copy of the ArrayList object, but both ArrayLists would end up referencing the same objects as elements of the List. In other words, after a shallow copy the folloowing two statements should be true:
originalList != copyOfList
originalList.get(0) == copyOfList.get(0)

By contrast, a deep copy of an ArrayList would not only copy the ArrayList object, but make copies of each of the elements as well (and copies of objects contained in each element object ad infinitum). After a deep copy, the collowing statements should hold true:
originalList != copyOfList
originalList.get(0) != copyOfList.get(0)
originalList.get(0).equals(copyOfList.get(0))

From this you can probably intuitively understand the differences between shallow and deep comparisons. I guess a shallow comparison of an two ArrayLists would only compare the actual ArrayList objects, whereas a deep comparison would compare the ArrayList objects as well as each element of the ArrayLists.
 
wood burning stoves
 
subject: Deep and Shallow Comparison!!