开发者

Using an iterator for a set of type Object?

Okay, so I'm supposed to implement a set that contains elements of type Object with no duplicates which means that I need to compare each new element with the previous elements in the set. The set has its own class and has a method for inserting a new element.

My question is: How do I use the it开发者_运维百科erator I wrote below to compare all the entries in the set with the proposed element to add?

class SetIterator implements MyIterator {
    private ArraySet arr;  //ArraySet is the name of the Set class
    private int n;

    SetIterator(ArraySet myArraySet)
    {
        arr = myArraySet;
        n = 0;
    }

    @Override
    public boolean hasNext() 
    {
        return (n <= arr.size());
    }

    @Override
    public Object next()
    {
        if (hasNext())
            return arr[n++];
    }   
}

Thanks!


You'd need something like this in ArraySet.java.

public Iterator iterator()
{
    return new SetIterator(this);
}

public boolean add(Object o)
{
    for (Object item : this)
        if (o.equals(next)) return false;
    }
    // add code to put o in the array
    return true;
}

The for loop is translated by the compiler to something like this:

Iterator it = this.iterator();
while (it.hasNext())
{
    Object item = it.next();
    if (o.equals(next)) return false;
}


The implementation of Set should guarantee no-duplication rather than the Iterator.

That is, your Set.add() and its constructor with Collection as argument should guarantee no-duplication. The Iterator just implements hasNext(), next(), and remove().

If Iterator takes care of duplication checking, your Set will violate java.util.Set contract. Moreover, the Iterator will take two responsibilities—checking duplication and traversing, that violates “Single Responsibily Principle”.


Yes, I just want an example on how to use that iterator instead of a for loop or a while loop.

You pretty much have to use some kind of loop to use a Iterator. Here is the basic pattern:

Iterator it = ... // instantiate the iterator
while (it.hasNext()) {
    Object obj = it.next();
    ... // do something with obj
}

If the collection object (e.g. your set of objects) implements Iterable then you can use the new for loop syntax; e.g.

for (Object obj : yourSet) {
    ... // do something with obj
}

Of course, there are other ways to express this, but they all involve (somewhere) a loop of some kind to pull the objects from the iterator.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜