我正在编写一个Java程序,打印两个集合的笛卡儿积。我用迭代器定义了两个TreeSets。
当我在两个集合(嵌套迭代)中使用while语句进行迭代时,问题是,只有第二个正在完成所有元素。迭代器似乎彼此混淆了。
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如果set1 = {1,2}和set2 = {1,2},则得到这个输出:(1,1)(1,2),其中期望输出为:(1,1)(1,2) (2,1)(2,2)
提前感谢^_^
发布于 2013-04-06 21:35:54
如果您希望计算笛卡儿积,则需要重新初始化第一个迭代器的每个值的第二个迭代器。
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 whilehttps://stackoverflow.com/questions/15856240
复制相似问题