I’m reading a book about data structures in java, and it’s talking about iterators now. I saw the following code and it seems odd to me. In the following code, AbstractIterator is an abstract class that implements Iterator<E>, UniqueFilteris a subclass of AbstractIterator that is not abstract, and data is a Vector. I guess I don’t understand how in the first line you can take the output of the Vector.iterator() method and cast that into an abstract class. After line 1, is dataIterator not an instantiated instance of an abstract class?
AbstractIterator<String> dataIterator =
(AbstractIterator<String>)data.iterator();
AbstractIterator<String> ui = new UniqueFilter(dataIterator);
The problem is that there are two different types we are talking about. The (run time) type of an object and the (compile time) type of a reference.
dataIteratoris a reference of an abstract type – that’s ok.data.iterator()returns a reference to an object whose type is not clear from the example, but apparently it’s a concrete type which inherits fromAbstractIterator<String>– that’s okSo after line one
dataIteratoris still a reference of typeAbstractIterator<String>, but it’s a reference to an object of a concrete type which implementsAbstractIterator<String>.Remember, in JAVA all the object variables are actually references.
UniqueFilteris irrelevant for this question, btw.