String Iteration using Iterator interface in Lists

120 Views Asked by At

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!!

2

There are 2 best solutions below

0
On

"... In the above code, Can someone explain this line String course = (String) iterator.hasNext(); why have they give String in brackets()? ..."

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.

for(Iterator<String> iterator = courses.iterator(); iterator.hasNext();){
    String course = iterator.next();
    System.out.println(course);
}

"... And, why semicolon after iterator.hasNext(); in for loop ..."

That's the syntax.  They are not using any increment value.

for (initialization; termination; increment) {
    statement(s)
}

Finally, just iterate courses.

for (String s : courses) System.out.println(s);
2
On
  1. (String) is called a "cast". It converts from one type (Object) to another (String). It was more necessary before generics and parametrized types (Iterator<String>). Before generics, you could only get elements of type Object (the root of all types) out of a collection. If you wanted to call String methods on your element, you had to cast it to a String. This would fail at runtime if the thing was actually, say, an Integer.

  2. Those semicolons are a required part of the for loop syntax. It's usually for something to happen at the end of your iterations, normally incrementing an index variable. As you're not using an index variable, it's a noop (no operation, do nothing) in your case.

Since Java 1.5 prefer this terser syntax:

    for (String course : courses) {
        System.out.println(course);
    }

And since Java 9 use List.of() for creating the list (creates an immutable list, which for most purposes is advantageous):

    List<String> courses = List.of("Java", "Python", "C");