-2

I have two arrayLists that contain objects of my Class Report Object. Report Object has couple of fields but most important are Tag(String) and Attr(String).

During the execution of the program two arrayLists are populated with that objects. These arrayLists represent old collection of the ReportObjects and the new one.

I want to know what objects were added to the new arrayList and what objects were removed from old ArrayList.

ReportObject obj1 = new ReportObject("Tag", "Attr", "XPath", "Parent", null);
    ReportObject obj2 = new ReportObject("Tag2", "Attr", "XPath", "Parent", null);
    ReportObject obj3 = new ReportObject("Tag", "Attr", "XPath", "Parent", null);
    ArrayList<ReportObject> newList = new ArrayList<>();
    ArrayList<ReportObject> oldList = new ArrayList<>();
    ArrayList<ReportObject> added = new ArrayList<>();
    ArrayList<ReportObject> removed = new ArrayList<>();
    newList.add(obj1);
    newList.add(obj2);
    oldList.add(obj3);
    added.addAll(newList);
    added.removeAll(oldList);

Problem is I still have two elements in added ArrayList. That because obj1 and obj3 are different objects? When I do two loops and iterate over them while checking if objects has same field values i still get same results.

So in added arrayList I should have only obj2 and in removed arrayList should be empty.

dharr
  • 318
  • 1
  • 11

3 Answers3

2

A String is an Object in Java. This will work. Java Collections make heavy use of equals to determine if an object is present in the collection. If you don't override equals, this will remove only objects that are present in both collections. That usually is the intended result though.

Chris Thompson
  • 33,380
  • 11
  • 76
  • 105
0

I guess you have an ID on the class you're making an object, then go like this:

for(ReportObject obj : xmlModel_New)
{
int i = 0;
    for(ReportObject obj2 : xmlModel_Old){

    if(obj.get(i).getId() != obj2.get(i).getId())
    {

        addedTags.add(obj);
    }
    i++;
    }
}

Something like that.

Frakcool
  • 10,088
  • 9
  • 41
  • 71
0

You need to override the equals(Object obj) and hashCode() method in the ReportObject class. The default uses the memory location which I doubt is how you are trying to compare them. What makes them equal? One attribute or all the attributes? You have to define that. Your example would change to...

    if(!obj.equals(obj2))
    {
        addedTags.add(obj);
    }

I think this question is being downvoted probably because it has been answered before or maybe because it is kind of unclear what you are asking. Post more details and I will try to help.

Also, check out some of these links:

What issues should be considered when overriding equals and hashCode in Java?

How do I compare strings in Java?

Community
  • 1
  • 1
Andrew Campbell
  • 16,015
  • 2
  • 13
  • 23