This week's book giveaway is in the JavaScript forum.
We're giving away four copies of JavaScript Promises Essentials and have Rami Sarieddine on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Comparing two Collections for Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of JavaScript Promises Essentials this week in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Comparing two Collections for "equality"" Watch "Comparing two Collections for "equality"" New topic
Author

Comparing two Collections for "equality"

Gavin Bong
Ranch Hand

Joined: Apr 25, 2003
Posts: 56
I have two Collections A and B. Both contain the same object types.
I want to compare both Collection for equality. This is how I am
doing it now. Pseudocode follows:

Does anybody see any holes in the logic / code above ?
Thanks all
Gavin
Jeanne Boyarsky
author & internet detective
Marshal

Joined: May 26, 2003
Posts: 30894
    
158

You are assuming that all the objects have an equals method defined? (this assumption is ok, I just want to state it.)
You may run into trouble if the collections contain duplicates. For example if collection a is [X,X,Y] and collection b is [X,Y,Y], your code will not catch the difference.
If the collections can't contain duplicates, the second check for containsAll is redundant.


[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
Gavin Bong
Ranch Hand

Joined: Apr 25, 2003
Posts: 56
Jeanne,
Thanks for your observations.
The parameters "can" and "may" contain duplicates.
I wonder whether I can just simplify it by doing

Gavin
[ October 01, 2003: Message edited by: Gavin Bong ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Comparing two Collections for "equality"