-2

I am supposed to implement an iterator that returns an iterator over the items in random order. This is what I have tried to do for now:

    private class RandomQueueIterator<E> implements Iterator<E> {
    int i = -1;

    public boolean hasNext() {
        return i+1 < size;
    }
    public E next() {
        if (!hasNext()) {
            throw new java.util.NoSuchElementException();
        }
        i++;
        return (E) queue[i];
    }
    public void remove() {
        throw new java.lang.UnsupportedOperationException();
    }

}

public Iterator<Item> iterator() { // return an iterator over the items in random order
    return new RandomQueueIterator();
}

I have an idea that I am supposed(?) to use StdRandon.uniform(); but have no idea where to write it exactly. I was therefore hoping one of you guys could help me!

rama96x
  • 9
  • 1
  • 1
    Please [take the tour](http://stackoverflow.com/tour) to see how the site works and what questions are on topic here, and [edit] your question accordingly. See also: [Why is "Can someone help me?" not an actual question?](http://meta.stackoverflow.com/q/284236) – Joe C Feb 17 '18 at 12:11
  • Welcome to Stack Overflow! Please take the [tour] and read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) Your "tried to do for now" is just an iterator, there is no attempt at all to handle making it random. So...do your research, [search](/help/searching) for related topics on SO, and give it a go, try to do it. ***If*** you get stuck and can't get unstuck after doing more research and searching, post a [mcve] of your attempt and say specifically where you're stuck. People will be glad to help. Good luck! – T.J. Crowder Feb 17 '18 at 12:12
  • Thank you for the answer's guys! I'm not quit sure how you would want me to formulate my question. If you are asking for the other half of the code, I can gladly send it to you, even though I find it irrelevant in relation to this topic. Could you guys be more specifik of what you want me to elaborate on or anything?? Thanks in advance! – rama96x Feb 17 '18 at 12:28

1 Answers1

1

I think that the easiest way would be to copy the list you want to iterate, and shuffle that:

List<E> shuffled = new ArrayList<>(list);
Collections.shuffle(shuffled);

Then just use shuffled.iterator().

Andy Turner
  • 137,514
  • 11
  • 162
  • 243