Question

Array with Iterator. Java style

Implement an array data structure as a class JstyArray<E> to support the Iterable interface such that the following code works:

JstyArray<Integer> data;

data = new JstyArray<Integer>(10);

for (int i = 0; i < 10; ++i) {
    data.set(i, new Integer(i) );
}

int sum = 0;
for ( int v : data ) {
    if (v == null)
        continue; // empty cell
    sum += v;
}

The iterator provided by this class follows the behaviour of typical Java style (Jsty). If the underlying collection is modified, the iterator becomes invalid and an exception is raised.

An example of code that may generate an exception is below:

try {
    int sum = 0;
    for ( int v : data ) {
        if (v == null) continue;
        if (v < 7)
            data.remove(0); // remove the first element
        // continue looping
        sum += v;
    }
} catch (NoSuchElementException nsee) {
    // ... handle as needed
}

There are 4 necessary methods for the Array. get(), set(), remove() and iterator().

There are 2 necessary methods for Iterator. hasNext() and next().

Other than these, you need to create more methods for communicating between Array and the Iterator. Object references are very useful in this scenario.

Once you have an iterator going. There is the next step of handling multiple iterators for the same data structure. More than one iterator can exist, at different times. There are iterators which are

•are invalid and have raised an exception, or

•are invalid and have not yet raised an exception, or

•are valid, they were created after modification to the data structure.

Multiple iterators are one of the harder tests

THERE ARE TWO CLASSES USED as shown below:

....................................................................................................................

JstyIterator.java:

/*
* An iterator for the class JstyArray. Performs all standard tasks of an iterator.
* Specifically, when calling next() on an invalid iterator, a NoSuchElementException is raised by this class.
*
*/
import java.util.Iterator;
import java.util.NoSuchElementException;

public class JstyIterator implements Iterator{

private JstyArray array;

private int index;

public JstyIterator(JstyArray array) {

this.array = array;

index = 0;

}

// YOUR CODE ANYWHERE IN THIS CLASS

public boolean hasNext() {

// YOUR CODE ANYWHERE IN THIS CLASS

if (array.size == index)

return false;

else
return true;

}

public E next() throws NoSuchElementException {

// YOUR CODE ANYWHERE IN THIS CLASS

if (array.list.size() != array.size)

throw new NoSuchElementException("Array elements have been modified !");

else if (hasNext()) {

return array.get(index++);

} else {

throw new NoSuchElementException("There are no elements in the array. Size = " + array.size);

}

}

public void remove() {

// we need this method for the nagging Java compiler

// you may leave empty

}

}

..........................................................................................................................................................

JstyArray.java:

/*
* An array that implements the Iterable interface.
* Returns an iterator that would raise an exception if the array was modified (set or remove)
*
*/

import java.util.LinkedList;

public class JstyArray implements Iterable{

// YOUR CODE ANYWHERE IN THIS CLASS

private E[] array;

public static final int CAPACITY = 100;

public int size;

public int capacity;

public LinkedList list;

// there could be more instance variables!

/*
* initialise array with capacity. If capacity is less than 1, use CAPACITY.
*
*/

@SuppressWarnings("unchecked")

public JstyArray(int capacity) {

// YOUR CODE ANYWHERE IN THIS CLASS

if (capacity
{

array = (E[]) new Object[CAPACITY];

this.capacity = CAPACITY;

list = new LinkedList();

size = 0;

}

else

{

array = (E[]) new Object[capacity];

this.capacity = capacity;

list = new LinkedList();

size = 0;

}

}

/*
* if index is outside range of array. simply return
*
*/

public void set(int i, E val) {

// YOUR CODE ANYWHERE IN THIS CLASS

if (i >= capacity)

return;

else

{

array[i] = val;

list.add(i, val);

size++;

}

}

/*
* if index is outside range of array. return null
*
*/

public E get(int i) {

// YOUR CODE ANYWHERE IN THIS CLASS

if (i >= capacity)

return null;

else

return array[i];

}

/*
* if index is outside range of array. return null
*
*/

public E remove(int i) {

// YOUR CODE ANYWHERE IN THIS CLASS

if (i >= capacity)

return null;

else

{

list.remove(i);

E e = array[i];

array[i] = null;

return e;

}

}

public JstyIterator iterator() {

// YOUR CODE ANYWHERE IN THIS CLASS

return new JstyIterator(this);

}

}

.........................................................................................................................................................................

It passes some testcase but not all.

TESTCASES testremove Begin4 V testPrintEachNoExcep

Can you fix my code for it to pass all testcases

0 0
Add a comment Improve this question Transcribed image text
Answer #1

PROGRAM CODE:

JstyArray.java

package array2;

/*

* An array that implements the Iterable interface.

* Returns an iterator that would raise an exception if the array was modified (set or remove)

*

*/

import java.util.LinkedList;

import java.util.NoSuchElementException;

public class JstyArray<E> implements Iterable<E>{

// YOUR CODE ANYWHERE IN THIS CLASS

private E[] array;

public static final int CAPACITY = 100;

public int size;

public int capacity;

public LinkedList<E> list;

// there could be more instance variables!

/*

* initialise array with capacity. If capacity is less than 1, use CAPACITY.

*

*/

@SuppressWarnings("unchecked")

public JstyArray(int capacity) {

// YOUR CODE ANYWHERE IN THIS CLASS

if (capacity<1)

{

array = (E[]) new Object[CAPACITY];

this.capacity = CAPACITY;

list = new LinkedList<E>();

size = 0;

}

else

{

array = (E[]) new Object[capacity];

this.capacity = capacity;

list = new LinkedList<E>();

size = 0;

}

}

/*

* if index is outside range of array. simply return

*

*/

public void set(int i, E val) {

// YOUR CODE ANYWHERE IN THIS CLASS

if (i >= capacity)

return;

else

{

array[i] = val;

list.add(i, val);

size++;

}

}

/*

* if index is outside range of array. return null

*

*/

public E get(int i) {

// YOUR CODE ANYWHERE IN THIS CLASS

if (i >= capacity)

return null;

else

return array[i];

}

/*

* if index is outside range of array. return null

*

*/

public E remove(int i) {

// YOUR CODE ANYWHERE IN THIS CLASS

if (i >= capacity)

return null;

else if(array[i] == null)

{

   throw new NoSuchElementException("No such element !");

}

else

{

list.remove(i);

E e = array[i];

array[i] = null;

//size--;

return e;

}

}

public JstyIterator<E> iterator() {

// YOUR CODE ANYWHERE IN THIS CLASS

return new JstyIterator<E>(this);

}

}

JstyIterator.java

package array2;

/*

* An iterator for the class JstyArray. Performs all standard tasks of an iterator.

* Specifically, when calling next() on an invalid iterator, a NoSuchElementException is raised by this class.

*

*/

import java.util.Iterator;

import java.util.NoSuchElementException;

public class JstyIterator<E> implements Iterator<E>{

private JstyArray<E> array;

private int index;

private int initialSize;

public JstyIterator(JstyArray<E> array) {

this.array = array;

this.index = 0;

this.initialSize = array.list.size();

}

// YOUR CODE ANYWHERE IN THIS CLASS

public boolean hasNext() {

// YOUR CODE ANYWHERE IN THIS CLASS

if (array.size == index)

return false;

else

return true;

}

public E next() throws NoSuchElementException {

// YOUR CODE ANYWHERE IN THIS CLASS

if (initialSize != array.list.size())

throw new NoSuchElementException("Array elements have been modified !");

else if (hasNext()) {

return array.get(index++);

} else {

throw new NoSuchElementException("There are no elements in the array. Size = " + array.size);

}

}

public void remove() {

// we need this method for the nagging Java compiler

// you may leave empty

}

}

JstTester.java

package array2;

import java.util.NoSuchElementException;

public class JstTester {

   static JstyArray<Integer> array;

  

   public static void main(String[] args) {

       array = new JstyArray<>(10);

       for(int i=0; i<10; i++)

           array.set(i, i);

       //Test case - testRemoveBegin4

       array.remove(4);

       //Test case - testPrintEachNoException

       System.out.println("\nTest case - testPrintEachNoException");

       JstyIterator<Integer> itr = array.iterator();

       while(itr.hasNext())

       {

           System.out.print(itr.next() + " ");

       }

       System.out.println("");

       //Test case - testRemoveBegin4

       array.remove(5);

      

      

      

       System.out.println("\nTest case - testConsecutiveBad");

       itr = array.iterator();

       array.remove(1);

       try{

           while(itr.hasNext())

       {

           System.out.print(itr.next() + " ");

       }}catch (NoSuchElementException e) {

           System.out.println("Exception: Error: " + e.getMessage());

       }

      

       itr = array.iterator();

       System.out.println("\nTest case - testConsecutiveGood");

       while(itr.hasNext())

       {

           System.out.print(itr.next() + " ");

       }

       System.out.println("");

      

       try

       {

       array.remove(5);

       }catch (Exception e) {

           System.out.println("\nException: Error: " + e.getMessage());

       }

   }

}

OUTPUT:

Test case - testPrintEachNoException

0 1 2 3 null 5 6 7 8 9

Test case - testConsecutiveBad

Exception: Error: Array elements have been modified !

Test case - testConsecutiveGood

0 null 2 3 null null 6 7 8 9

Exception: Error: No such element !

Add a comment
Know the answer?
Add Answer to:
Array with Iterator. Java style Implement an array data structure as a class JstyArray<E> to support...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Java implement the method in IteratorExercise.java using only list iterator methods: bubbleSort: sort the provided list...

    Java implement the method in IteratorExercise.java using only list iterator methods: bubbleSort: sort the provided list using bubble sort Do not modify the test code in each function. You can look at that code for some ideas for implementing the methods. import java.lang.Comparable; import java.util.*; public class IteratorExercise {       public static <E extends Comparable<? super E>> void bubbleSort(List<E> c) throws Exception {        // first line to start you off        ListIterator<E> iit = c.listIterator(), jit;...

  • Can someone please explain this piece of java code line by line as to what they...

    Can someone please explain this piece of java code line by line as to what they are doing and the purpose of each line (you can put it in the code comments). Code: import java.util.*; public class Array { private Integer[] array; // NOTE: Integer is an Object. Array() {     super();     array = new Integer[0]; } Array(Array other) {     super();     array = other.array.clone(); // NOTE: All arrays can be cloned. } void add(int value) {    ...

  • java create java program that make stack with LinkedList and stack is implement iterator. When stack’s iterator call next(), it pop its data. here is the example of output //by user 5 1 2 3 4 5 //then...

    java create java program that make stack with LinkedList and stack is implement iterator. When stack’s iterator call next(), it pop its data. here is the example of output //by user 5 1 2 3 4 5 //then output comes like this 5 4 3 2 1 Stack is empty. here is the code that i'm going to use class Stack<T> implements Iterator<T> {    LinkedList<T> list;       public Stack() {        list = new LinkedList<T>();    }       public boolean isEmpty() {        return list.isEmpty();   ...

  • Consider the following class definition class FibSequence implements Iterablexnteger public Iterator<Integer> iterator) return new FibIterator); private class FibIterator implements Iterator&lt...

    Consider the following class definition class FibSequence implements Iterablexnteger public Iterator<Integer> iterator) return new FibIterator); private class FibIterator implements Iterator<Integer> f //complete this You are required to create an inner class in the FibSequence class. The inner class should be called FibIterator. It implements the Iterator<Integer> interface and implements the hasNext() and the next() methods. The iterator iterates through the Fibonacci sequence. The Fibonacci sequence is a series of numbers where a number is the sum of previous two numbers....

  • When compiling the LinkedList and Iterator class, the following error is being produced: Note: LinkedList.java uses...

    When compiling the LinkedList and Iterator class, the following error is being produced: Note: LinkedList.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details. Any suggestions? public class LinkedList<T> {    Node<T> itsFirstNode;    Node<T> itsLastNode;    private int size;    public LinkedList() {        itsFirstNode = null;        itsLastNode = null;          size = 0;    }    public Iterator<T> getIterator() {        return new Iterator(this);    }    // THIS WILL NEED...

  • Java: Return an array of booleans in a directed graph. Please complete the TODO section in...

    Java: Return an array of booleans in a directed graph. Please complete the TODO section in the mark(int s) function import algs13.Bag; import java.util.HashSet; // See instructions below public class MyDigraph { static class Node { private String key; private Bag<Node> adj; public Node (String key) { this.key = key; this.adj = new Bag<> (); } public String toString () { return key; } public void addEdgeTo (Node n) { adj.add (n); } public Bag<Node> adj () { return adj;...

  • Complete P16.1 and P16.4 (Class Name: NewMethodDemo) Once complete, upload all .java files. For primary test...

    Complete P16.1 and P16.4 (Class Name: NewMethodDemo) Once complete, upload all .java files. For primary test class: Remember your header with name, date, and assignment. Also include class names that will be tested. Psuedocode (level 0 or mixture of level 0 and algorithm [do not number steps]) is required if main() contains more than simple statements (for example, your program includes constructs for decisions (if/else), loops, and methods. For Secondary class(es): Include a JavaDoc comment that describes the purpose of...

  • Java Programming: The following is my code: import java.util.Arrays; public class KWArrayList<E> {    // Data...

    Java Programming: The following is my code: import java.util.Arrays; public class KWArrayList<E> {    // Data fields    /** The default initial capacity */    private static final int INITIAL_CAPACITY = 10;       /** The underlying data array */    private E[] theData;       /** The current size */    private int size = 0;       /** The current capacity */    private int capacity = 0;       @SuppressWarnings("unchecked")    public KWArrayList() {        capacity...

  • Improve the speed of public T get(int i) by having it work backward from the end...

    Improve the speed of public T get(int i) by having it work backward from the end of the array if you attempt to get a member which is closer to the end than the start. This improvement will be tested through timing tests on large lists. The method should still return null if i is not a valid index. Code import java.util.Iterator; public class DLList<T> implements Iterable<T> {    private static class Node<T> {        public Node<T> prev, next;...

  • In Java Language. Modify the LinkedPostionalList class to support a method swap(p,q) that causes the underlying...

    In Java Language. Modify the LinkedPostionalList class to support a method swap(p,q) that causes the underlying nodes referenced by positions p and q to be exchanged for each other. Relink the existing nodes, do not create any new nodes. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- package lists; import java.util.Iterator; import java.util.NoSuchElementException; public class LinkedPositionalList implements PositionalList { //---------------- nested Node class ---------------- /** * Node of a doubly linked list, which stores a reference to its * element and to both the previous and next...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT