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.
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.
The latter. The generic argument avoids explicit casts, and helps you maintain type-safety. However, String is not Iterable.
In the latter form, the Iterator is strongly typed which is preferable
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?")
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);