Possible Duplicate:
What is a raw type and why shouldn't we use it?
The question is pretty much self contained in the description: what is the difference between
Iterator<?>
and
Iterator
objects in java? They both iterate over Object types right?
Nope.
Iterator<?>iterates over?s (some type that derives fromObject), whileIteratoronly providesObjects. This is the generics support in Java.What’s a
?type? Well, that’s a great question.Back in the bad old days before Java 5, you had untyped collections and untyped iterators. So you’d have
Objects in your collections and you’d have to cast them manually. For example:Notice that cast? That’s because we’re just stuffing
Objects into lists, and we have to do all that housekeeping ourselves. Not so bad with just aList, but imagine a map that contains a map that contains a map that contains a … well, you get the idea. You’re in casting hell and you can pretty quickly not know whether you’re looking at a map that goes fromStringtoIntegeror your other map that goes backwards fromIntegertoString.In Java 5, you can use generics, so now you can say:
Note that the cast was unnecessary? When we use a
List<String>, we can use anIterator<String>and have some type safety.This is really beneficial when you start doing things with more complex data structures, like: