The following code doesn't work. What's wrong with this code? Compiler complains in the for loop that NumberList
isn't a Iterable
class.
What kind of class can be used in for-each loop? How to make NumberList
iterable? I tried making NumberList implement Iterable
, but it doesn't seem to work because I don't know how to define the Iterator properly.
If someone could demonstrate how to make this code work, or link me to a tutorial that'd be great.
public class Test{
public class NumberList{
private int numItems;
private Number[] numbers;
public NumberList(int size){
this.numbers = new Number[size];
this.numItems=0;
}
public void add(Number n){
this.numbers[this.numItems++]=n;
}
}
public void printPairs() {
ArrayList<Integer> num=new ArrayList<Integer>();
NumberList numbers = new NumberList(50);
numbers.add(4);
numbers.add(5);
numbers.add(6);
for(Number n1: numbers){
System.out.println(n1);
}
}
}
The error can only iterate over an array or an instance of java. lang. iterable doesn't mean that it stops the user from using a loop on an array or an instance. It means that a loop is used that doesn't complement its conditions - for example, the for or foreach loop.
NumberList does not implement Iterable. As far as the compiler is concerned its just any other class.
You need to do something like this
public class NumberList implements Iterable<Number> {
private int numItems;
private Number[] numbers;
public NumberList(int size) {
this.numbers = new Number[size];
this.numItems = 0;
}
public void add(Number n) {
this.numbers[this.numItems++] = n;
}
@Override
public Iterator<Number> iterator() {
return Arrays.asList(numbers).subList(0, numItems).iterator();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With