Home > OS >  Iterator.iter() returns same values
Iterator.iter() returns same values

Time:10-12

I'm working on a simple java project that implements playlist for songs. My program should be able to add songs to the playlist, and have functionality to skip forward, repeat and skip backwards. I'm trying to write a simple method that when called will skip songs, but it always returns the same elements. Please read my comments in the code below to better understand my question.

Here is the simplified example:

import java.util.LinkedList;
import java.util.ListIterator;

public class testClass {

    public static void main(String[] args) {

        LinkedList<String> list = new LinkedList<>();
        // Add elements to the list. 
        list.add("First Element");
        list.add("Second Element");
        list.add("Third Element");
        
        ListIterator<String> iter = list.listIterator();
        // If I call this method it works and returns next elements.
        System.out.println(iter.next()); 
        System.out.println(iter.next()); 
        System.out.println("======================");
        // However this method returns same elements no matter how  many times I call it.
        // Why does this happen and how can I fix it ? 
        skip(list); 
        skip(list); 
        // outputs : 
        //First Element
        //Second Element
        ==================
        //First Element
        //First Element
    }
    public static void skip(LinkedList<String> stringList) {
        ListIterator<String> iter = stringList.listIterator();
        if(iter.hasNext())
            System.out.println(iter.next());
    }

}

CodePudding user response:

You need to iterate in a while loop, not an if statement. I have modified your method to below:

public static void skip(LinkedList<String> stringList) {
        ListIterator<String> iter = stringList.listIterator();
        while (iter.hasNext())
            System.out.println(iter.next());
    }

CodePudding user response:

That is because you calling skip(list); twice, every time you call it it'll start from the first item.

The statements of .next() move to next index in your list after print it you just need to remove one of skip(list); and edit your skip function to be like this :

    public static  void skip(LinkedList<String> stringList) {
    ListIterator<String> iter = stringList.listIterator();
    if(iter.hasNext()){
        System.out.println(iter.next());
        System.out.println(iter.next());
    }
        
}

or like this to print all item in the list :

    public static void skip(LinkedList<String> stringList) {
    ListIterator<String> iter = stringList.listIterator();
     while (iter.hasNext())
        System.out.println(iter.next());  
}
  • Related