Reputation: 767
I wonder why at place (), it returns different values. In the constructor, it returns me 3, which makes sense. However, in the second (), it returns 0. I thought both places should return 0. Am I missing something here?
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Vector2D implements Iterator<Integer> {
private List<List<Integer>> vec2d;
private Iterator<Integer> it;
private int counter = 0;
private int size;
public Vector2D(List<List<Integer>> vec2d) {
this.vec2d = new ArrayList<List<Integer>>();
if(vec2d.size() == 0) {
this.it = null;
} else {
this.size = vec2d.size();
System.out.println("this size is " + size); // * returns 3
this.it = vec2d.get(0).iterator();
}
}
@Override
public Integer next() {
System.out.println("what happens here? " + vec2d.size()); **// * why it returns 0?? should it return 3??**
if(hasNext()) {
return it.next();
}
return -1;
}
@Override
public boolean hasNext() {
if(it == null) {
return false;
}
while(counter < size) {
if(it.hasNext()) {
return true;
}
counter++;
if(counter >= size) {
return false;
}
System.out.println("counter is " + counter + " size is " + vec2d.size());
List<Integer> l = vec2d.get(counter);
it = l.iterator();
}
return false;
}
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
List<Integer> list2 = new ArrayList<Integer>();
List<Integer> list3 = new ArrayList<Integer>();
list.add(1);
list.add(2);
list2.add(3);
list3.add(4);
list3.add(5);
list3.add(6);
List<List<Integer>> lists = new ArrayList<List<Integer>>();
lists.add(list);
lists.add(list2);
lists.add(list3);
Vector2D vec = new Vector2D(lists);
System.out.println(vec.next());
}
}
Upvotes: 0
Views: 45
Reputation: 1254
You have to assign your attribute the value from constructor parameter otherwise you are working with the Parameter vec2d
and not with your Attribute vec2d
:
public Vector2D(List<List<Integer>> vec2d) {
this.vec2d = vec2d;//assign Parameter to list
if(this.vec2d.size() == 0) {
this.it = null;
} else {
this.size = this.vec2d.size();
System.out.println("this size is " + size); // * returns 3
this.it = this.vec2d.get(0).iterator();
}
}
Just try to rename the List<List<Integer>> vec2d
method param to something else and you will see.
Upvotes: 3