Why can't an iterator return a concrete data type?

97 Views Asked by At

In Java, why can't iterator return a concrete data type. For example:

//access via Iterator
Iterator iterator = queueA.iterator();
while(iterator.hasNext(){
    String element = (String) iterator.next();
}

I have to cast it to String explicitly. Why cannot an iterator return String automatically?

1

There are 1 best solutions below

2
On BEST ANSWER

Iterator is a generic class, just like Queue. You should declare your iterator as such:

Iterator<String> iterator = new queueA.iterator();