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 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;
No difference, except that the compiler will be happier with the first one, because then it knows that you don't care what the Iterator returns ;-)
In the second case the compiler may give warnings, because the type is unspecified and can't be checked. Lots of warnings everywhere means that you don't notice the ones that actually matter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With