Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterator<?> vs Iterator in java [duplicate]

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?

like image 403
Bober02 Avatar asked Dec 06 '22 15:12

Bober02


2 Answers

Nope. Iterator<?> iterates over ?s (some type that derives from Object), while Iterator only provides Objects. 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:

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 Objects 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;
like image 55
Edward Thomson Avatar answered Dec 21 '22 09:12

Edward Thomson


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.

like image 22
DNA Avatar answered Dec 21 '22 11:12

DNA