[英]hasPrevious() Method not working
I don't understand why my hasPrevious iterator is not functioning, it looks like this:我不明白为什么我的 hasPrevious 迭代器不起作用,它看起来像这样:
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.我有另一个使用 hasNext() 的函数,它可以工作,但这个函数不行。
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.我不确定这种方法是否不再存在,但是当我查看它时,Java 网站提到了它。 I don't understand why it is not functioning.我不明白为什么它不起作用。
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. hasPrevious
和previous
方法只为 ListIterators ( http://docs.oracle.com/javase/1.5.0/docs/api/java/util/ListIterator.html ) 定义,这是 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 .由于您只使用迭代器,因此唯一定义的方法是hasNext()
、 next
和remove
- 请参见此处: http : //docs.oracle.com/javase/1.5.0/docs/api/java/util/Iterator。 .html
Only the ListIterator
can walk backwards.只有ListIterator
可以向后走。 The normal Iterator
class can't.普通的Iterator
类不能。
So if you use ListIterator
instead of Iterator
it will work :)因此,如果您使用ListIterator
而不是Iterator
它将起作用:)
It should be like this:应该是这样的:
public void previousSong(){
ListIterator<Song> it = songs.listIterator();
while(it.hasNext()) {
System.out.println(it.next().toString());
}
// and now you can use hasprevious()
while(it.hasPrevious()) {
System.out.println(it.previous().toString());
}
}
// Create an array list
ArrayList list = new ArrayList();
// add elements to the array list
list.add("C++");
list.add("Java");
list.add("Php");
list.add("Python");
list.add("Ruby");
list.add("Perl");
//Create the object of ListIterator through listIterator() method
ListIterator object=list.listIterator();
// Modify the list element
while(object.hasNext()) {
String language=(String) object.next() ;
object.set(language+"+");
}
// Show element in pervious order
while(object.hasPrevious()) {
System.out.println(object.previous());
}
It should work by first implementing in forward direction then in backward direction.它应该首先在正向实施,然后在反向实施。
don't use Iterator in this Interface hasPrevious() function is not defined use ListIterator不要在此接口中使用 Iterator hasPrevious() 函数未定义使用 ListIterator
ListIterator lt =al.listIterator(al.size());
while(lt.hasPrevious())
{
System.out.println(lt.previous());
}
this will take into the last location of the collection object这将考虑到集合对象的最后一个位置
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.