0

I'm writing an app and at some point I have to compare two arraylist or two objects, I defined a class called Article and wrote this code to compare two articles

    public boolean aredifferent(){

    Article art1 = new Article();
    art1.setBm(null);
    art1.setDesc("he");
    art1.setImagelink("www");
    art1.setLink("www");
    art1.setTitle("ti");

    Article art2 = new Article();
    art2.setBm(null);
    art2.setDesc("he");
    art2.setImagelink("www");
    art2.setLink("www");
    art2.setTitle("ti");
    boolean diff;
    if(art1.equals(art2)){
        diff = false;
    }else{
        diff = true;
    }


    return diff;

}

the problem I'm having that this method is returning true and I can't see why. any ideas? is there a different way to compare objects in android?

Thank you

1

2 Answers 2

0

Check how equals() is implemented for that class, best guess is that you haven't overridden the equals() method and it is relying on Object 's implementation

0

I'm assuming that you haven't defined a custom "equals" method for your Article class? If so, the reason why art1.equals(art2) is always returning false is because the default equal method in Java works by checking if the two objects have the same address in memory.

Because you're creating two different Article instances, they will obviously not share the same memory address and so equals will always return false. You can test this by doing something like art1.equals(art1) -- in that case, your method will behave as expected.

To fix this, you need to override the equals method in the Article class and create a new version that explicitly checks against the fields in the Article class. (You should also probably define a custom version of hashCode that uses those same fields.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.