Manage Differences Between Two Arraists
My question is, am I going to compare two arraylists in Java
eg
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
array1.add(obj1);array1.add(obj2);array1.add(obj3);
//array 2 has 2 objects
array2.add(obj1);array2.add(obj2);
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:
if(!methodToCompareArrays(array1,array2)){
//HOW TO GET THE DIFFERENT objects (IN THIS CASE, obj3 is the different object)
//this is the question :)
}else{
//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
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
same.
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);
intersection.retainAll(set2);
if(intersection.size() == set2.size()) {
// They're the same.
} else {
HashSet<MyObject> itemsOnlyInSet1 = intersection;
HashSet<MyObject> itemsOnlyInSet2 = set2.retainAll(set1);
}
source to share
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.
source to share