It's not a secret anymore!
The moose likes Beginning Java and the fly likes How do I can compare two arraylists? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How do I can compare two arraylists?" Watch "How do I can compare two arraylists?" New topic

How do I can compare two arraylists?

D Hagy

Joined: Jul 05, 2011
Posts: 12
I have two arraylists like arraylist1 and arraylist2. I need to compare them and if they are not equal I need to take another action, than if they are equal. How I can compare all ints in these arrays and how I can compare them? I think one equal method is not enough.
Rob Spoor

Joined: Oct 27, 2005
Posts: 20188

Are you talking about ArrayLists or about arrays?
Usually, simply using the equals method of Lists should be good enough. This will use the equals method of all its elements. However, sometimes that's not good enough, in those cases where the elements have an equals method you can't use. Arrays are such objects.

I am assuming you have a List<int[]>. If this is correct, then you indeed cannot use equals itself. You will need to create a utility method that checks if two List<int[]> objects are equal. They are equal if:
1) they have the same size
2) each element is equal

You need to iterate over the elements of both Lists; you can then use Arrays.equals to check for the array equality.

How To Ask Questions How To Answer Questions
fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11923

The first thing you need to do is decide for yourself what you consider equal array lists to be. A few things to consider:

1) Can arrays of different sizes still be equal? If one array is size 10, and another is 5, can they still be equal?

2) Does the order of the elements in the array matter?

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
subject: How do I can compare two arraylists?
jQuery in Action, 3rd edition