Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How To Compare to Iterators...............?

 
Hanuma Deepak Muvvala
Ranch Hand
Posts: 158
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,
Is there any method in collections framework classes to compare two iterators,r else can any body suggest how to compare iterators in java.

Regards,
Deepak........
 
Purushoth Thambu
Ranch Hand
Posts: 425
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Iterator is just a pointer. I am not sure what you want to compare? If you want to see if both iterator points to same object then == should work. If you want to compare iterators that point to different collection (to check if both the collection contains same elements) then you can use
- containsAll(Collection c) api something like below:

public boolean isEqual(Collection a, Collection b)
{
return a.containsAll(b) && b.containsAll(a);
}
 
Hanuma Deepak Muvvala
Ranch Hand
Posts: 158
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have to compare the contents of the lists pointed by these two iterators,i.e. those 2 lists have same values r not.........
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So you mean you want to compare two Lists not two Iterators? Well since a List is a Collection Purushothaman Thambu has already posted the code that lets you do that.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Note that the code shown verifies that all elements of a are in b, and all elements of b are in a. You may need to consider: do you care about the order? Is [1, 2, 3] the same as [3, 2, 1]? What about duplicates? Is [1, 2, 2] the same as [1, 2] or [1, 1, 2]? If these lists are considered different, you may wish to use the equals() method already defined in List:

or maybe

It really depends what you want to do...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic