I was learning Collections in JAVA from a tutorial. In that during List topic I saw a line where we use a line to iterate the lists of type String in for loop using Iterator. Please refer to the piece of code below and help me to understand the concept,
List <String> courses = Arrays.asList("Java","Python","C");
for(Iterator iterator = courses.iterator();iterator.hasNext();){
String course = (String) iterator.hasNext();
System.out.println(course);
}
In the above code, Can someone explain this line
String course = (String) iterator.hasNext();
why have they give String
in brackets()?
And, why semicolon after iterator.hasNext();
in for
loop
Appreciating your response in advance!!
This code is poorly abstracted.
Firstly, it should be the next method, and not the hasNext method.
The reason String is in parentheses is because of the type-cast syntax.
In this situation, a type-parameter for iterator was not declared, thus Object is used.
If you provide the type-parameter you can remove the cast.
That's the syntax. They are not using any increment value.
Finally, just iterate courses.