More advanced usage of interfaces

Posted by owca on Stack Overflow See other posts from Stack Overflow or by owca
Published on 2010-04-12T03:56:30Z Indexed on 2010/04/12 4:03 UTC
Read the original article Hit count: 407

Filed under:
|
|
|
|

To be honest I'm not quite sure if I understand the task myself :) I was told to create class MySimpleIt, that implements Iterator and Iterable and will allow to run the provided test code. Arguments and variables of objects cannot be either Collections or arrays.
The code :

 MySimpleIt msi=new MySimple(10,100,
                           MySimpleIt.PRIME_NUMBERS);

 for(int el: msi)
   System.out.print(el+" ");    
 System.out.println();

 msi.setType(MySimpleIterator.ODD_NUMBERS);
 msi.setLimits(15,30);
 for(int el: msi)
   System.out.print(el+" ");    
 System.out.println();

 msi.setType(MySimpleIterator.EVEN_NUMBERS);
 for(int el: msi)
   System.out.print(el+" ");    
 System.out.println();

The result I should obtain :

11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 


15 17 19 21 23 25 27 29 


16 18 20 22 24 26 28 30

And here's my code :

import java.util.Iterator; 
interface MySimpleIterator{
    static int ODD_NUMBERS=0;
    static int EVEN_NUMBERS = 1;
    static int PRIME_NUMBERS = 2;

    int setType(int i);
}

public class MySimpleIt implements Iterable, Iterator, MySimpleIterator {    
    public MySimple my;

    public MySimpleIt(MySimple m){ 
        my = m;      
    }

    public int setType(int i){
        my.numbers = i;
        return my.numbers;
    }

    public void setLimits(int d, int u){
        my.down = d;
        my.up = u;
    }

    public Iterator iterator(){
        Iterator it = this.iterator();
        return it;
    }

    public void remove(){  
    }

    public Object next(){
        Object o = new Object();
        return o;
    }

    public boolean hasNext(){
        return true;
    }

}

class MySimple {
    public int down;
    public int up;
    public int numbers;

    public MySimple(int d, int u, int n){
        down = d;
        up = u;
        numbers = n;
    }
}

In the test code I have error in line when creating MySimpleIt msi object, as it finds MySimple instead of MySimpleIt. Also I have errors in for-each loops, because compiler wants 'ints' there instead of Object. Anyone has any idea on how to solve it ?

© Stack Overflow or respective owner

Related posts about java

Related posts about interface