1

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?

user3815165
  • 258
  • 2
  • 16
  • Have you tried implementing `Comparable`? old.compareTo(X) will then indicate whether or not they are equal. http://stackoverflow.com/questions/3718383/java-class-implements-comparable – Ian2thedv Sep 10 '14 at 10:45
  • What doesn't work about that statement? What did you expect to happen, and what actually _did_ happen? – nhaarman Sep 10 '14 at 10:46
  • all field are equals but condition old.equals(x) false – user3815165 Sep 10 '14 at 10:55

2 Answers2

1

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;
}
Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64
0
public boolean equals(Object object2) {
    return object2 instanceof MyClass && a.equals(((MyClass)object2).a);
}
Sagar Pilkhwal
  • 3,998
  • 2
  • 25
  • 77