File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes What is the use of Clone and Equal? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "What is the use of Clone and Equal?" Watch "What is the use of Clone and Equal?" New topic
Author

What is the use of Clone and Equal?

Jenson Chew
Ranch Hand

Joined: May 27, 2007
Posts: 55
May I know what is the usage of Clone and Equal in Java? I think we won't be using them in most if not all of the application development daily, do we?

Are they important?Or should I just skp go through and understand that there are such things exist in Java?

I'm still learning from the Java 1.6 Tutorial and just want to clear some of my doubts here =)

Regards,
Jenson


:: Vision is Power ::
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
The clone() method and the Cloneable interface are still used, but they are something from very early Java that was not very well thought-out. Still, they are a useful way of getting a shallow copy of a Java object, without doing much coding and without needing that code to be updated when the fields of the object change.

Alternatives to clone(), for creating copies of objects, include: -
  • write a constructor that takes a reference to another object of same class (a copy-constructor)
  • serialise and deserialise. Take care about transient fields. Not very efficient.
  • write to XML and read back. Probably done a lot these days. Horribly inefficient.


  • I don't know what you mean by "Equal". Please explain. There's the Object.equals() method, or the identity operator "==". Or did you mean something else?


    Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
    Jenson Chew
    Ranch Hand

    Joined: May 27, 2007
    Posts: 55
    Originally posted by Peter Chase:
    The clone() method and the Cloneable interface are still used, but they are something from very early Java that was not very well thought-out. Still, they are a useful way of getting a shallow copy of a Java object, without doing much coding and without needing that code to be updated when the fields of the object change.

    Alternatives to clone(), for creating copies of objects, include: -
  • write a constructor that takes a reference to another object of same class (a copy-constructor)
  • serialise and deserialise. Take care about transient fields. Not very efficient.
  • write to XML and read back. Probably done a lot these days. Horribly inefficient.


  • I don't know what you mean by "Equal". Please explain. There's the Object.equals() method, or the identity operator "==". Or did you mean something else?

    Hi Peter,

    Thanks for your clarification. However, I still don't understand what you mean in your elaboration, I think mainly due to the fact that I'm still learning the basics on that.

    For the Equal, sorry, that's my mistake, actually I mean equals, like what you mentioned on top, obj.equals(), sorry.

    I was puzzled whether we will be using it in anyway, since according to you, they are not so efficient.

    Regards,
    Jenson
    Bill Cruise
    Ranch Hand

    Joined: Jun 01, 2007
    Posts: 148
    Jenson,

    The equals() method is used quite a lot. It's purpose is to determine whether two objects have the same value. Remember, when dealing with objects the "==" operator works on the references. That is, "==" tells you if your two references are pointing to the same object. You can write an equals method that tells you if two objects contain the same data.

    Here's a good reference I use to remind myself what the elements of a good equals method are:
    ]http://www.geocities.com/technofundo/tech/java/equalhash.html]
    ]http://www.geocities.com/technofundo/tech/java/equalhash.html[/url]

    As for the clone() method, as Peter mentioned above, it's an older technique that isn't used as much any more. It's good to know that it exists, what it does, and what methods (listed above) can be used in its place.
    Peter Chase
    Ranch Hand

    Joined: Oct 30, 2001
    Posts: 1970
    Originally posted by Jenson Chew:
    For the Equal, sorry, that's my mistake, actually I mean equals, like what you mentioned on top, obj.equals(), sorry.

    I was puzzled whether we will be using it in anyway, since according to you, they are not so efficient.


    I didn't say anything about the efficiency of equals() method. But equals() is still used a lot and is, I'd say, essential to know about.

    The implementation of equals() in java.lang.Object is very efficient. All it does is compare two object references to see if they are identical (pointing to the same object).

    Unfortunately, the implementation of equals() in java.lang.Object is quite often not what you want, because you want the test for equality to look at the values stored inside the object, not just the object's identity. Therefore, it is often necessary to override the equals() method in your classes, to look at the values, in a way appropriate to your class (which java.lang.Object could not possibly know).

    Whether a particular overridden equals() method is efficient depends on how complicated the test for equality is, for that class of object, and how well it has been coded. There's no general statement to be made: some will be very efficient and some rather inefficient.
    Jenson Chew
    Ranch Hand

    Joined: May 27, 2007
    Posts: 55
    Originally posted by Bill Cruise:
    Jenson,

    The equals() method is used quite a lot. It's purpose is to determine whether two objects have the same value. Remember, when dealing with objects the "==" operator works on the references. That is, "==" tells you if your two references are pointing to the same object. You can write an equals method that tells you if two objects contain the same data.

    Here's a good reference I use to remind myself what the elements of a good equals method are:

    Here


    As for the clone() method, as Peter mentioned above, it's an older technique that isn't used as much any more. It's good to know that it exists, what it does, and what methods (listed above) can be used in its place.


    Hi Bill,

    Hmm, I'm still quite confused there, can't even catch a glimpse of how to use it and where would it most likely be used in the codes. I will read up the link given by you and try to understand them. Heavy stuff for me, maybe due to lack of experience in actual coding? Sigh... But thanks for the reply =)
    Jenson Chew
    Ranch Hand

    Joined: May 27, 2007
    Posts: 55
    Originally posted by Peter Chase:


    I didn't say anything about the efficiency of equals() method. But equals() is still used a lot and is, I'd say, essential to know about.

    The implementation of equals() in java.lang.Object is very efficient. All it does is compare two object references to see if they are identical (pointing to the same object).

    Unfortunately, the implementation of equals() in java.lang.Object is quite often not what you want, because you want the test for equality to look at the values stored inside the object, not just the object's identity. Therefore, it is often necessary to override the equals() method in your classes, to look at the values, in a way appropriate to your class (which java.lang.Object could not possibly know).

    Whether a particular overridden equals() method is efficient depends on how complicated the test for equality is, for that class of object, and how well it has been coded. There's no general statement to be made: some will be very efficient and some rather inefficient.


    Hi Peter,

    Sorry that I get you wrong. Now I can only understand that we do use these two methods but how to use it in daily coding and when and where to use it is still a confusing point for me. I'm somehow lost there...uhhh...I suddengly feel that I'm so dumb
    Bill Cruise
    Ranch Hand

    Joined: Jun 01, 2007
    Posts: 148
    The equals method should be a part of your daily coding if you spend any significant amount of time writing code. I'll give you a simple example. Say I create an Employee class that consists of an employee id number, a name, and a hire date (just for simplicity).



    Now let's say I have some client code that needs to compare two Employee objects to each other to decide it they're the same (maybe I'm hiring a new employee and want to make sure he's not already on the payroll). What I want the client code to do is something like this:

    *** RIGHT WAY ***


    instead of something like this:

    *** WRONG WAY ***


    The reason the second way is wrong is that it is only comparing the two references to see if they point to the same object. You don't want that. You want to look a little deeper, into the objects themselves to see if they contain the same data.

    You can do that using the equals method. But what should you compare to decide if two objects are equal? That's up to you. Every Java class gets to decide what defines equality for that class. In the Employee example I could compare the names of the two employees, but that wouldn't be very smart. Two people can have the same name. I could go a step further in this direction and compare the names and the hire dates. That would be a lot better. It's really unlikely that two people with the same name got hired on the same day. You can do even better than that, though. Employee ID numbers *should* be unique, so my equals method might look something like this:



    Of course this is highly simplified. You should use the guidelines in the page linked to above to find out about writing a solid equals method.

    Hope this clears things up.
    David McCombs
    Ranch Hand

    Joined: Oct 17, 2006
    Posts: 212
    posted Today 12:29 PM Profile for Bill Cruise Send New Private Message Edit/Delete Post Reply With Quote The equals method should be a part of your daily coding if you spend any significant amount of time writing code. I'll give you a simple example. Say I create an Employee class that consists of an employee id number, a name, and a hire date (just for simplicity).

    code:

    public class Employee
    {
    private int empId;
    private String name;
    private Date hireDate;

    // constructors go here

    // getters & setters go here
    }



    Now let's say I have some client code that needs to compare two Employee objects to each other to decide it they're the same (maybe I'm hiring a new employee and want to make sure he's not already on the payroll). What I want the client code to do is something like this:

    *** RIGHT WAY ***

    code:

    if(employee1.equals(employee2)){
    // do something useful
    }



    Unless equals is overridden, that will not determine if the 2 objects representing employees are the same person, it will determine if the 2 references point to the same object, which might not tell you enough. The following code assumes that equals is not overridden.



    From the API docs:

    Indicates whether some other object is "equal to" this one.

    The equals method implements an equivalence relation on non-null object references:

    * It is reflexive: for any non-null reference value x, x.equals(x) should return true.
    * It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
    * It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
    * It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
    * For any non-null reference value x, x.equals(null) should return false.

    The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).

    Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.


    So you can see it only checks reference values, not object values. It returns true if 2 references are a equivalence relation and is consistent. But as the docs simplify:

    for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true)


    Which makes sense because there is no possible way that Object could ever know about its children. The Integer class overrides equals, for example, so as long as the reference type is Integer and not Object, you will get the behavior you expect.



    To properly compare Employees, you can use the Comparable interface, and/or override equals. http://java.sun.com/j2se/1.5.0/docs/api/index.html This will allow you to compare one objects members against another, to see if the objects are the same, or one is less then or greater then the other.

    This assumes that the number is always unique and is used to differentiating employees that share the same name.


    To answer the original question about equals. It is useful but not nearly as much as compareTo(). If you need to know if 2 references are pointing to the same object in memory, then you use equals from the Object class. If you need to know if the data inside two objects are the same you use the Comparable interface or equals if it is overridden in the Class, . If you need to know if 1 object is less then, equal to , or greater then, use Comparable and in more complex situations, Comparator.

    I have never had occasion to use clone().
    [ June 06, 2007: Message edited by: David McCombs ]

    "Should array indices start at 0 or 1? My compromise of 0.5 was rejected without, I thought, proper consideration."- Stan Kelly-Bootle
    Mark Dexter
    Ranch Hand

    Joined: Jun 03, 2007
    Posts: 34
    This is a confusing subject (at least to me!). One problem is that there is no generic "right" way to tell if two objects are equal. (Perhaps equivalent would be a better word.) It really does depend on the application.

    Some IDE's can automatically generate equals and hashcode methods for you. For example, Eclipse basically takes all of an object's fields (or the ones you choose) and makes sure that both objects have no null fields and that all of their fields are equal. If this is true, then they are equal.

    One other note: according to Joshua Block in Effective Java, you need to override the hashcode method whenever you override equals. (Eclipse does this as well.)

    Hope this helps. Mark Dexter
    Jenson Chew
    Ranch Hand

    Joined: May 27, 2007
    Posts: 55
    Yes it is confusing. Hmm, I think I would not get the idea easily until the day I really need to code something with .equals() But at least now I know whenever I need to overwrite the equals() I have to overwrite the hash too.

    Confusing me deeply. Now I also know what's the different between == and equals and when to use them, and which should you use most of the time.

    Well, to understand how to use it is one thing, how to apply it in the code is another thing I guess.

    Argh, this is going to kill me! I haven't master the basic and they throw me this headache equals page in Java tutorial. Now at least somehow clearer to me. The link given by Bill is quite useful in understanding one of the scenario when you will use it and how to put it inside your code.

    I guess I have to read more books or resources on that in a more simplified way and some more useful examples. Examples given by you guys so far give me a brief idea on the occasion when it's necessary and efficient to use that to achieve certain tasks.

    Java is really broad and need a lot of time to digest, I'm still chewing the sweet part of it, and now come the little bitter part
    David McCombs
    Ranch Hand

    Joined: Oct 17, 2006
    Posts: 212
    To simplify. Object.equals() compares the value of the reference(ie the location of memory of the object. If both references refer to the same object true is returned.

    If equals is overridden, there is usually a test against a object member(like with Integer).
    Jenson Chew
    Ranch Hand

    Joined: May 27, 2007
    Posts: 55
    Originally posted by David McCombs:
    To simplify. Object.equals() compares the value of the reference(ie the location of memory of the object. If both references refer to the same object true is returned.

    If equals is overridden, there is usually a test against a object member(like with Integer).


    Hey David,

    Thanks for shedding the light on me, that works! I think your simplified explanation helps. You've cleared the clog for me further

    Regards,
    Jenson
    arulk pillai
    Author
    Ranch Hand

    Joined: May 31, 2007
    Posts: 3219
    I strongly reccomend you to get a copy of Effective Java by Josh Bloch

    Clone() method should be used very judiciously.

    The ==

    The == returns true, if the variable reference points to the same object in memory. This is a �shallow comparison.






    The equals()


    returns the results of running the equals() method of a user supplied class, which compares the attribute values. The equals() method provides �deep comparison� by checking if two objects are logically equal as opposed to the shallow comparison provided by the operator ==.

    If equals() method does not exist in a user supplied class then the inherited Object class's equals() method is run which evaluates if the references point to the same object in memory. The object.equals() works just like the "==" operator (i.e shallow comparison).

    Overriding the Object class may seem simple but there are many ways to get it wrong, and consequence can be unpredictable behavior.





    [ June 06, 2007: Message edited by: arulk pillai ]
    [ June 06, 2007: Message edited by: arulk pillai ]

    Java Interview Questions and Answers Blog | Amazon.com profile | Java Interview Books
     
    With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
     
    subject: What is the use of Clone and Equal?
     
    Similar Threads
    CSharp and Java
    Question regarding Cloneable interface and Subclasses
    When and why to use Cloneable interface in java?
    My interview questions
    Array clone