Search code examples
javaarraylistiteratorlistiterator

Adding to a ListIterator of an ArrayList Object


I'm writing a program that manipulates an ArrayList with ListIterator without using any ArrayList methods. The ArrayList in this case is supposed to behave like a set.

My add method traverses the ArrayList and compares each element with the number to be added so that repeats can be avoided. OurSet() is the constructor of the class. I also redefine the toString method to print using ListIterator methods.

When I tested these two methods, it appeared that the add method didn't actually added anything (or the print statement isn't showing it). The output using the main method below is blank, and I'm not quite sure why. I traced through the code a few times, and placed print statements in the methods to make sure that they did run through every line. In the toString method, it never enters the while loop. The code is below, and any help is appreciated!

OurSet()
{
//      list is the ArrayList object, it was defined earlier and now instantiated
    list = new ArrayList();
//      iter is the ListIterator object, it was defined earlier and now instantiated
    iter = list.listIterator();
}

public void add(int x)
{
    while(iter.hasNext())
    {
        int item = (Integer) iter.next();
        if(item == x)
            break;
    }
    iter.add(new Integer(x));
}

public String toString()
{
    String set = "";
    while(iter.hasNext())
    {
        int item = (Integer) iter.next();
        set += item + " ";
    }
    return set;
}

Here is my main method.

public static void main(String args[])
{
    OurSet set = new OurSet();
    set.add(50);
    System.out.println(set);
}

Solution

  • Instantiating an IteratorList object will cause it to start back from the beginning. Since the only time I instantiated the object was in the constructor, it had already reached the end of the list in the add method and the toString method couldn't loop through it again. By re instantiating iter in toString method, the list was printed out properly.