user3815165
user3815165

Reputation: 258

clone object in java

I have a class X:

public class X implements Cloneable {
    private int a;
    private int b;

    @Override
    public X clone() throws CloneNotSupportedException {
        return (X) super.clone();
    }
}

I want to remember its initial state. Therefore get his clone:

try {
            old = new X();
            old = x.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }

x - an object of class X, a and b installed. For example i do with old:

old.setA(7)

How do I now compare the old and the new object, find out whether there were changes. I do so but does not work:

//if object is changed
if (!old.equals(x)){
}

How to check the object has changed or not?

Upvotes: 1

Views: 491

Answers (2)

Prabhakaran Ramaswamy
Prabhakaran Ramaswamy

Reputation: 26094

Add below code in your X class

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + a;
    result = prime * result + b;
    return result;
}
@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    X other = (X) obj;
    if (a != other.a)
        return false;
    if (b != other.b)
        return false;
    return true;
}

Upvotes: 1

Sagar Pilkhwal
Sagar Pilkhwal

Reputation: 3993

public boolean equals(Object object2) {
    return object2 instanceof MyClass && a.equals(((MyClass)object2).a);
}

Upvotes: 0

Related Questions