Sayadi
Sayadi

Reputation: 150

Nested TreeSet iterators - Java

I'm trying to write a Java program that prints the Cartesian Product of two sets. I defined two TreeSets with iterators.

The problem is when I'm iterating around both sets (nested iterating) using while statement, only the the second while is completing all the elements. It seems that iterators are getting confused with each other.

while (iSet1.hasNext()) { // to iterate over the first set
        int i = iSet1.next();

        while (iSet2.hasNext()) { // to iterate over the second set
            int j = iSet2.next();               
            System.out.printf("(%d,%d)",i,j);
        } // end of inner while
    } // end of outer while

if set1 = {1,2} and set2 = {1,2} I'm getting this output: (1,1)(1,2) where the desired output is: (1,1)(1,2) (2,1)(2,2)

thanks in advance ^_^

Upvotes: 0

Views: 512

Answers (1)

flup
flup

Reputation: 27104

If you wish to compute the cartesian product, you'll need to re-initialize the second iterator for each value of the first iterator.

while (iSet1.hasNext()) { // to iterate over the first set
    int i = iSet1.next();
    iSet2 = secondSet.iterator(); // <- re-initialize the iterator here
    while (iSet2.hasNext()) { // to iterate over the second set
        int j = iSet2.next();               
        System.out.printf("(%d,%d)",i,j);
    } // end of inner while
} // end of outer while

Upvotes: 2

Related Questions