简体   繁体   中英

How to implement the Iterable<> method in a generic class

I'm creating a generic class SortedArray that implements Iterable. My big problem is that I'm lost as to what I need to return for this particular method, or for that matter if I'm missing a major step in implementing it. With this current code when I compile it in Unix I'm getting an error stating inconvertible types. Any feedback or information that could put me on my way to fixing this would be much appreciated. Thank you.

public class SortedArray< T extends Comparable< T > >
    extends Object
    implements Iterable < T > {

    private T[] internalArray;
    public Iterator<T> iterator() {
        return (Iterator<T>) Arrays.asList(internalArray).iterator();
    }
}

Usually, you create an inner class that implements Iterator interface and that's what you return in iterator method. Here's an example:

//removed extends Object. The compiler will add this info for you
public class SortedArray<T extends Comparable<T>> implements Iterable<T> {

    private T[] internalArray;

    private class SortedArrayIterator implements Iterator<T> {
        int currentIndex;
        public SortedArrayIterator() {
            this.currentIndex = 0;
        }
        @Override
        public boolean hasNext() {
            return currentIndex < maxSize;
        }
        @Override
        public T next() {
            return internalArray[currentIndex++];
        }
        @Override
        public void remove() {
            for (int i = currentIndex; i < internalArray.length - 1; i++) {
                internalArray[i] = internalArray[i+1];
            }
        }
    }

    public Iterator<T> iterator() {
        return new SortedArrayIterator();
    }
}

Not directly related to your question, but there are few problems when working with generic arrays. Make sure you create this private T[] internalArray using the right approach, which is storing Class<T> somewhere, or maintain a Comparable[] internalArray instead, as shown in How to create a generic array in Java?

There is only a warning for the redundant cast. When the cast is removed (and the redundant extends Object ), it compiles:

public class SortedArray< T extends Comparable<T>>
    implements Iterable < T > {

    private T[] internalArray;
    public Iterator<T> iterator() {
        return Arrays.asList(internalArray).iterator();
    }
}

Compiles OK.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM