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
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();
}
}
}