I just found this exam question in an old exam paper and am readying myself for an upcoming exam. I cannot figure it out :
The following depicts a contrived partial
private class PartialIterableClass implements Iterable<String> {
private String[] things;
public PartialIterableClass( String[] things ){
this.things = things;
}
@Override
public Iterator<String> iterator() {
return Arrays.asList(things).iterator();
}
}
You can use ArrayIterator
, or build your own iterator like this:
package arrayiterator;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class ArrayIterator_int
{
public static void main(String[] args)
{
int [] arr = { 5, 4, 3, 2, 1 };
ArrayIterator_int iterator = new ArrayIterator_int(arr);
while (iterator.hasNext())
{
System.out.println(" " + iterator.next());
}
}
private int cursor;
private final int [] array;
private static final Lock lock = new ReentrantLock();
public ArrayIterator_int (int [] array)
{
this.array = array;
this.cursor = 0;
}
public boolean hasNext ()
{
boolean hasNext = false;
lock.lock();
try
{
hasNext = ((this.cursor+1) < this.array.length);
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
lock.unlock();
return hasNext;
}
}
public int next () throws ArrayIndexOutOfBoundsException
{
int next = 0;
lock.lock();
try
{
next = this.array[++this.cursor];
}
catch(ArrayIndexOutOfBoundsException e)
{
throw e;
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
lock.unlock();
return next;
}
}
public int read () throws ArrayIndexOutOfBoundsException
{
int read = 0;
lock.lock();
try
{
read = this.array[this.cursor];
}
catch(ArrayIndexOutOfBoundsException e)
{
throw e;
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
lock.unlock();
return read;
}
}
public void write (int newVal) throws ArrayIndexOutOfBoundsException
{
lock.lock();
try
{
this.array[this.cursor] = newVal;
}
catch(ArrayIndexOutOfBoundsException e)
{
throw e;
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
lock.unlock();
}
}
}
The easiest thing to do would probably be to create a new ArrayList<String>()
populated with the values in things
, and return the result of a call to its .iterator()
method. That's certainly what I'd do in a situation with limited time (like an exam), and quite likely what I'd do in a real-world scenario, just to keep things simple.
You could write your own ArrayIterator
class, or use one from various libraries you can find around the web, but it seems like that would add unnecessary complexity.
Your Iterator
must implement all the methods from the Iterator
interface in order to encapsulate the iteration logic.
In your case, it will have to hold the current iteration index in the array. You can look at ArrayIterator from commons-collections