我正在学习Java,我对ListIterator有一个问题。我的代码返回"buongiorno",而我期望它打印"buongiorn",没有尾随的" o“。由于hasNext()函数的缘故,我预料到了这一点。我的代码使用递归。你能给我解释一下原因吗?
public static String creaStringa(List<Character> lista) {
System.out.println(lista.size());
ListIterator<Character> it = lista.listIterator();
return ricCrea(it);
}
public static String ricCrea(ListIterator<Character> it) {
if(!(it.hasNext())) {
return "";
else
return String.valueOf(it.next()) +ricCrea(it);
}发布于 2013-06-14 09:46:53
如果列表只有一个元素,那就更清楚了,假设是"b“。hasNext()实际上会返回true,next()会读取它,然后迭代就会结束。
说明:
如果在任何非空列表上调用Iterator<Object> it= list.iterator() (即使它只有一个元素),则会因为调用hasNext()而获得true。这是因为迭代器是在第一个元素之前初始化的:
b u n g i o r n o
^
i - iterator当你调用next()时,它会做两件事:
当它读取迭代器前面的元素时,
在您的示例中-它打印"b“,并在”u“之前停止:
b u n g i o r n o
^
i就在结尾之前:
b u n g i o r n o
^
i它实际上有下一个值- "o“。调用next()将读取该值并在o之后跳转。没有更多的元素。hasNext()将显示false,并且调用next()将导致异常。
技术详细信息:
迭代器是这样实现的:-当通过调用List上的iterator()来创建Iterator时,它的内部变量next指向列表的第一个元素。- hasNext()只是检查next是否为!= null。- next()返回next并设置next以显示下一个元素。
这是java.util.ArrayList迭代器(省略了一些细节):
public Iterator<E> iterator() {
return new Itr();
}
private class Itr implements Iterator<E> {
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;
public boolean hasNext() {
return cursor != size;
}
public E next() {
checkForComodification();
int i = cursor;
Object[] elementData = ArrayList.this.elementData;
cursor = i + 1;
return (E) elementData[lastRet = i];
}
}发布于 2013-06-14 09:35:49
对于最后一个"o“字符,ListIterator.hasNext()也将返回true (就像所有其他字符一样)。因此,else也会被执行。只有在获取到最后一个"o“之后,hasNext()才会返回false (因为它现在已经遍历了所有元素)。
这里需要注意的是,hasNext()只检查在next()调用中是否还有其他东西可供返回。它不会自己获取或跳过它。
发布于 2013-06-14 09:35:13
当迭代器在最后一个'n‘处并且调用ricCrea时,hasNext将返回true,next将返回'o’。
因此,您可能想要编写如下内容:
public static String ricCrea(ListIterator<Character> it) {
if (it.hasNext()) {
Character c = it.next();
if (it.hasNext()) {
return c + ricCrea(it);
}
}
return "";
}https://stackoverflow.com/questions/17099782
复制相似问题