Manage Differences Between Two Arraists

My question is, am I going to compare two arraylists in Java


String prop1 = "String"
String prop2 = "OtherString"
MyObject obj1 = new MyObject(prop1,prop2);
MyObject obj2 = new MyObject(prop1,prop2);
MyObject obj3= new MyObject(prop1,prop2);

ArrayList<MyObject> array1 = new Arraylist<>();
ArrayList<MyObject> array2 = new Arraylist<>();
//array 1 has 3 objects
//array 2 has 2 objects


With the compare method, I know these arrays are different

(My method returns false if the arrays have the same elements even if they are not in the same order, and true if they have the same elements)

So the method will return FALSE

My question is:

    //HOW TO GET THE DIFFERENT objects (IN THIS CASE, obj3 is the different object)
    //this is the question :)
    //If there is no difference, well, it doesn't matter too much


Note that I am going to have multiple objects in these arraylists and that the efficiency of the method is important (not important, but important at least). I saw the answers Here But I'm not sure which one would be better or worse

Thanks in advance.


source to share

3 answers

To do this, you should probably use java to install interfaces for this .

It is now important to have a good method equals

on MyObject

to compare if two are the MyObjects


Then you can use this documentation link above to check the intersection of two sets. If the elements in both sets have the same number of elements as in one set, then they are the same (regardless of order).

HashSet<MyObject> set1 = new HashSet<MyObject>(array1);
HashSet<MyObject> set2 = new HashSet<MyObject>(array2);

Set<MyObject> intersection = new HashSet<MyObject>(set1);

if(intersection.size() == set2.size()) { 
    // They're the same.
} else { 
    HashSet<MyObject> itemsOnlyInSet1 = intersection;
    HashSet<MyObject> itemsOnlyInSet2 = set2.retainAll(set1);




If the objects in these lists are not important to you, you can do something like:

array1.removeAll (array2);

This will remove from array1 all elements that exist in array2.

So if array1 = [obj1, obj2, obj3] and array2 = [obj1, obj2]

After removing RemoveAll:

array1 = [obj3] and array2 = [obj1, obj2]

If you cannot remove objects from one of the lists, make a temporary list and delete it to get an additional object.



I'm not sure if I understand what your question is, but if you are trying to compare and sort a list of objects the best option is to search for TreeMaps from the collections API. Try the following:

Difference between HashMap, LinkedHashMap and TreeMap



All Articles