Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How do I can compare two arraylists?

 
D Hagy
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Pie
Posts: 20511
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
fred rosenberger
lowercase baba
Bartender
Pie
Posts: 12097
30
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic