Communiquez avec les autres et partagez vos connaissances professionnelles

Inscrivez-vous ou connectez-vous pour rejoindre votre communauté professionnelle.

Suivre

How to compare two Arraylists which contain objects of the same class in Java?

user-image
Question ajoutée par Mohamed Mansour , Java Developer , Arrow Electronics
Date de publication: 2013/06/09

compare the objects using the methods compareTo(Collection list) and Collection.compare(Collection list)

Suppose a1, a2 are the arrays you want to compare then you can use Arrays.equals(a1,a2) or if a1, a2 contains nested arrays Arrays.deepEquals(a1,a2)

Utilisateur supprimé
par Utilisateur supprimé

To compare two objects of an arrylist, you can use comparator interface which is present in java.util.Comparator package.Comparator interface has compare method to compare two objects.
In your code ,the class for which you want to compare its objects should implement Comparator interface and you have to override compare method in that class.
so when you try to compare that objects using "equals()" method it in turn calls compare method .

Mohamed Abukar
par Mohamed Abukar , IT Consultant , Buuho Trading LLC

you can use org.apache.commons.collections.CollectionUtils, if u u do use this , then simply use subtract method to compare the two lists, but create to other lists before u do this.
On the other hand if u r not using Collection framework u can again create another two lists and compare the members of the class, and if member is on list1, that means it is not on list2 and vice verse.
this only works if the members of the lists are unique.

Utilisateur supprimé
par Utilisateur supprimé

what make two arraylists equals in your case, how about duplicates ?? does the order of the objects in the arraylist counts in the comparison ? this link may help : http://stackoverflow.com/questions/8589351/how-to-compare-two-arraylist

More Questions Like This