Reputation: 101
I have two lists a = {1,2,2,5,6,6,6,7}
and b = {2,3,3,6,6,6,8}
I want to get the equivalent elements, in this case, the output should be 2 *(2 = 2) and 9 * (6 = 6) Here is part of my code
Iterator aIt = a.iterator();
Iterator bIt = b.iterator();
Iterator tempIt = b.iterator();
int aNode = (Integer)aIt.next();
int bNode = (Integer)bIt.next();
Boolean isEquals = false;
while(aIt.hasNext()||bIt.hasNext()){
while(aNode<bNode){
aNode = (Integer)aIt.next();
}
while(aNode>bNode){
bNode = (Integer)bIt.next();
}
while(aNode==bNode){
tempIt = bIt;
while(aNode==bNode){
System.out.println(aNode + " = " + bNode);
bNode = (Integer)tempIt.next();
}
aNode = (Integer)aIt.next();
tempIt = bIt;
bNode = (Integer)tempIt.next();
isEquals = true;
}
if(isEquals){
bIt = tempIt;
isEquals = false;
}
}
However after I run the code I realise that what I pass is the reference of bIt
to tempIt
not the content. Is there any solution if I really want to use iterator to achieve this? Many thanks!
Upvotes: 0
Views: 232
Reputation: 1
I suspect that there's an easier way to do it---namely, not using iterators, but rather by using the lists themselves.
So if your lists A and B are ArrayList<Integer>
s, it might look something like this:
public void printMatch(ArrayList<Integer> A, ArrayList<Integer> B) {
for(int i = 0; i < A.length(); i++) {
for(int j = 0; j < B.length(); j++) {
if(A.get(i).equals(B.get(j))) {
System.out.println("Match!" + A.get(i));
}
}
}
}
Or something along those lines---I've not compiled that, but it's the right idea.
Upvotes: -1
Reputation: 335
It sounds like you want to clone your iterator, something that is not supported in Java (the clone()
method is private).
Just as a note, the iterator does not contain the data, you should think of it as an interface to the list. So maybe iterators is not the most ideal solution here.
Upvotes: 2