-3

Regarding type inference in Java, I have the following small snippet of code:

ArrayList<String> projectNameList = new ArrayList<String>(3);
projectNameList.add("Joe");
projectNameList.add("Jim");
projectNameList.add("Josh");

Iterator it = names.iterator();

while(it.hasNext()){
   System.out.println(it.next());
}

I get a compile error when I try to print the names saying Type mismatch: cannot convert from Object to String

I know that to fix this all I need to do is explicitly cast the Object to a String, or by explicitly declaring that the type of elements returned by this iterator are of type String, like so:

Iterator it<String> = names.iterator();

But I would have thought that the javac compiler would be clever enough to infer the type returned by the iterator are Strings, seen as the iterator() method is called on an ArrayList of Strings.

Any reason why this type inference does not take place?

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
fulhamHead
  • 687
  • 1
  • 10
  • 23

1 Answers1

2

Iterator is also a generic type.

You need to declare it as Iterator<String> it = names.iterator(); to reference its elements as Strings without casting.

Declaring it as a raw type will actually tell the compiler you want your reference to be an Iterator<Object>.

As mentioned by others, you won't get a compiler error by just printing the elements of your raw Iterator - you will if you reference a non-existing projectNameList variable instead of, say, names.

Mena
  • 47,782
  • 11
  • 87
  • 106