[英]Issue creating iterator in java
我正在尝试创建一个迭代器类来完成我认为的两个简单方法,但是我在创建迭代器时遇到了问题。 我创建迭代器的那一行给了我一个编译错误,说“迭代器是抽象的;不能被实例化”。 我不太确定这意味着什么,但显然我做错了什么。 此外,我将这些方法的目的放在它们上面,如果您发现它们有任何问题,请告诉我。 感谢您提供任何意见!
import java.util.Iterator;
private class OrderedListIterator{
Iterator<E> it = new Iterator<E>();
//return true if iterator has more items
public boolean hasNext(){
boolean found = false;
if(it.hasNext == true)
found = true;
return found;
return found;
}
//return next item in the iterator
public E getNext(){
if(it.hasNext != false)
return it.next;
}
//prints out message
public void remove(){
System.out.println("Operation not supported");
}
}
您收到此错误的原因是迭代器是一个接口。
在 Java 编程语言中,接口是一种引用类型,类似于类,只能包含常量、方法签名、默认方法、静态方法和嵌套类型。 方法体仅存在于默认方法和静态方法中。 接口不能被实例化——它们只能由类实现或由其他接口扩展。 本课稍后将讨论扩展。
来自 Java 文档https://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html
接口包含方法的定义,而不是实现,这就是您不能创建或调用接口或其方法的原因。 迭代器接口有两个方法; hasNext() 和 next()。 您的代码看起来像是要实现迭代器接口。
private class OrderedListIterator implements Iterator<E>
在您的 hasNext 和 next 方法中,您需要根据您的实现方式迭代 OrderedList。
这是我之前创建的 ArrayList 的迭代器示例。
private class ArrayIterator implements Iterator<E> {
private int arrayIndex = 0;
/**
* Checks if the set has a next value.
*
* @return true if there is a next value, else false
*/
public boolean hasNext() {
//Checks that the index is within the size of the ArrayList
return arrayIndex < size;
}
/**
* Gets the next value in the iteration.
*
* @return
* The next value in the list
* @throws NoSuchElementException
* if there is no next element in the list
*/
public E next() throws NoSuchElementException {
if (arrayIndex == size) {
throw new NoSuchElementException();
}
//Checks the ArrayList's data at the current index
return data[arrayIndex++];
}
}
您的私有类能够访问其周围类中的字段。 在我的示例中,迭代器在数组中存储一个索引(如内部游标)并在当前索引处检查 ArrayList 的数据。 每次调用 next 方法时,下一次都会增加索引。
如果 OrderedList 类类似于 LinkedList 并且具有节点,则您将保存对节点的引用,并且每次调用 next 方法时,您将返回该节点,然后将光标更改为下一个节点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.