tags:

views:

109

answers:

4

Which form is preferred:

String my = "Which form shall I use?";
Iterator iter = my.iterator();

or

Iterator<String> iter = my.iterator();

I personally preferr the former but in my materials from uni they use the latter.

+5  A: 

The latter. The generic argument avoids explicit casts, and helps you maintain type-safety. However, String is not Iterable.

Matthew Flaschen
+10  A: 

In the latter form, the Iterator is strongly typed which is preferable

ob1
+7  A: 

You should use generics when the API provides it. That is, the latter alternative is preferrable.

Iterator iter = someList.iterator();
String s = (String) iter.next();  // prone to class cast exceptions.
                                  // What if someone for instance accidentally
                                  // put a CharSequence in the list?

vs

Iterator<String> iter = someList.iterator();
String s = iter.next();           // guaranteed typesafe at compile-time.

(String does not implement Iterable<String> however, but I'm sure you meant something like List<String> my = Arrays.asList("Which form shall I use?")

aioobe
+2  A: 

String is not iterable? If you want to iterate over the characters you need to do something like this:

String my = "Which form shall I use?";
for(char c : my.toCharArray())
    System.out.println(c);
dacwe
true, the char array is iterable, but not the string itself (a string has-a char array, but it isn't one)
seanizer