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

Ram23
  • 91
  • 2
  • 10

4 Answers4

9

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

dacwe
  • 43,066
  • 12
  • 116
  • 140
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).

Community
  • 1
  • 1
Andrzej Doyle
  • 102,507
  • 33
  • 189
  • 228
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().

amicngh
  • 7,831
  • 3
  • 35
  • 54
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;
    }
Raji A C
  • 2,261
  • 4
  • 26
  • 31