4

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?

Community
  • 1
  • 1
Bober02
  • 15,034
  • 31
  • 92
  • 178
  • @ruakh: Sorry was trying to find similar question and was not aware how to word it. Thanks for a link. – Bober02 Mar 05 '12 at 20:00
  • 3
    No need to apologize. The only reason I could find that question is that I already knew that the answer was "raw types". I marked it as a duplicate to point you at the wonderful answers there, rather than to criticize your question for duplicating that one. – ruakh Mar 05 '12 at 20:02

3 Answers3

11

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;
Edward Thomson
  • 74,857
  • 14
  • 158
  • 187
3

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.

DNA
  • 42,007
  • 12
  • 107
  • 146
1

The first means that the objects that it iterates, they can be anything. The second one in practice is the same, but in theory is that you have no Generics there, so you are not using the advantages that the compiler provides.

Luciano
  • 8,552
  • 5
  • 32
  • 56