1

I have two arraylist with a number of model objects.I want to find the difference of these arraylists.When I use strings instead of models, I got the difference with removeall function in collection framework. But for model objects it doesnot work. Please any one help me

1
  • What do you mean by comparing two ArrayLists? Commented Jun 20, 2012 at 10:39

4 Answers 4

9

Implement equals and hashCode in your custom object and you can use the same approach as you did with Strings.

Sign up to request clarification or add additional context in comments.

Comments

0

Well, the removeAll method is a generic library method which doesn't know anything about your model class. So if you think about it for a second, how is it going to know which ones are "the same"?

The short answer is that you need to override the equals() method in your Model class, as this is what the checks are based on. The implementation should return true for any pair of model instances that you wish to be considered the same - the default inherited behaviour returns true only if they're the same object in memory. (And as always, when you override equals() you must override hashCode() too).

Comments

0

String class has already overridden version of equals and hashCode method so you are able to use remove() method. If you have to use your class in collection (List or Set) then you will have to override these methods in your class otherwise it will use default implementation of these methods.

If two objects are logically equal that means their hashCode must be equal as well as they satisfy equals().

Comments

0

For comparing two ArraList you need two compare two objects.In your case it is your model object,for that you need to override equals method. Try this code @Override public boolean equals(Object compareObj) { if (this == compareObj) return true;

    if (compareObj == null) 
        return false;

    if (!(compareObj instanceof MyModel)) 
        return false;

    MyModel model = (MyModel)compareObj; 

    return this.name.equals(model.name); // Are they equal?
    }

    @Override
    public int hashCode()
    {
    int primeNumber = 31;
    return primeNumber + this.name.hashCode();
        return 0;
    }

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.