Nope. Iterator<?>
iterates over ?
s (some type that derives from Object
), while Iterator
only provides Object
s. 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 Object
s in your collections and you'd have to cast them manually. For example:
List foo = new ArrayList();
foo.add("Foo!");
for(Iterator i = foo.iterator(); i.hasNext(); )
{
Object element = i.next();
System.out.println((String)element);
}
Notice that cast? That's because we're just stuffing Object
s into lists, and we have to do all that housekeeping ourselves. Not so bad with just a List
, 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 from String
to Integer
or your other map that goes backwards from Integer
to String
.
In Java 5, you can use generics, so now you can say:
List<String> foo = new ArrayList();
foo.add("Foo!");
for(Iterator<String> i = foo.iterator(); i.hasNext(); )
{
String element = i.next();
System.out.println(element);
}
Note that the cast was unnecessary? When we use a List<String>
, we can use an Iterator<String>
and have some type safety.
This is really beneficial when you start doing things with more complex data structures, like:
Map<String, Map<String, Map<String, SomeRandomObject>>> complexMap;