Skip to content
Advertisement

hasPrevious() Method not working

I don’t understand why my hasPrevious iterator is not functioning, it looks like this:

public void previousSong(){
    Iterator<Song> iterator = songs.iterator();
if(iterator.hasPrevious()) {
        System.out.println(iterator.previous().toString());
}
}

I have another function using hasNext() and it works, but this one will not.

public void nextSong(){
    Iterator<Song> iterator = songs.iterator();
if(iterator.hasNext()) {
        System.out.println(iterator.next().toString());
}
}

I am not sure if this method is no longer in existence or not, but when I look into it, Java websites speak of it. I don’t understand why it is not functioning.

Advertisement

Answer

The hasPrevious and previous methods are only defined for ListIterators (http://docs.oracle.com/javase/1.5.0/docs/api/java/util/ListIterator.html), a sub-interface of Iterator. As you’re only using an Iterator the only defined methods are hasNext(), next and remove – see here: http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Iterator.html.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement