Type mismatch: cannot convert from Item to Item

2020-03-30 02:46发布

public class RandomizedQueue<Item> implements Iterable<Item> {

    private Item[] s;
    private int N;

    public Iterator<Item> iterator() {
        return new RQIterator<Item>();
    }

    private class RQIterator<Item> implements Iterator<Item> {

        private Item[] copy;
        private int newItems;

        public RQIterator() {
            copy = (Item[]) new Object[N];
            for (int i = 0, k = 0; i < s.length; i++) {
                if (s[i] != null)
                    copy[k++] = s[i];
            }
            newItems = N;
        }

        //hasNext(), next(), remove() methods..
    }
}

On the line copy[k++] = s[i], I am getting the Error: Type mismatch: cannot convert from Item to Item, but I can't figure out what's wrong. Can somebody tell? Thanks!

1条回答
叼着烟拽天下
2楼-- · 2020-03-30 03:22

Your inner class RQIterator is declaring a new type parameter Item that is distinct from the type parameter Item that its enclosing class RandomizedQueue is declaring.

However, the Item type parameter from RandomizedQueue is still in scope, because RQIterator, as a nested class, isn't a static nested class. Just use Item from RandomizedQueue.

private class RQIterator implements Iterator<Item> {

Also the creation of the iterator in iterator() won't need the type parameter either.

public Iterator<Item> iterator() {
    return new RQIterator();
}
查看更多
登录 后发表回答