gpt4 book ai didi

java - 循环链表和迭代器

转载 作者:太空宇宙 更新时间:2023-11-04 12:56:46 25 4
gpt4 key购买 nike

我无法让迭代器实际工作并测试我的 add 和 next 方法。我想知道是否有人可以指出我缺少什么。我已经研究了一段时间,似乎无法弄清楚如何正确初始化对象,一直说无法解析为类型。谢谢这是我的主课

public class CircularList<E> { 
private int size = 0;

//Inner Class
private static class Node<E>{
private E data;
private Node<E> next=null;
private Node<E> previous=null;

private Node(E dataItem) {
data = dataItem;
}
}


//Iterator
public class CircleIter implements ListIterator<E>{
private Node<E> nextItem;
private Node<E> lastItemReturned;
private int index = 0;

public CircleIter(){
nextItem=null;
lastItemReturned=null;
}

@Override
public void add(E data) {
Node<E> newNode = new Node<E>(data);
if(index==0){
newNode.next=newNode;
newNode.previous=newNode;
nextItem=newNode;
lastItemReturned=newNode;
}
else{
newNode.previous=nextItem.previous;
nextItem.previous.next=newNode;
newNode.next=nextItem;
nextItem.previous=newNode;

}
index++;
size++;
}

@Override
public boolean hasNext() {
return nextItem != null;
}

@Override
public boolean hasPrevious() {
return (lastItemReturned.next == null && size != 0)
|| lastItemReturned.previous != null;
}

@Override //need to look over
public E next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
lastItemReturned = nextItem;
nextItem = nextItem.next;
index++;
return lastItemReturned.data;
}
@Override
public int nextIndex() {
return index;
}

@Override //need to look over
public E previous() {
nextItem=lastItemReturned;
lastItemReturned=lastItemReturned.previous;
index--;
return nextItem.data;
}
@Override
public int previousIndex() {
return index-1;
}

//remove last item returned through next&previous method
@Override
public void remove() {
if (lastItemReturned == null) {
throw new IllegalStateException();
}
nextItem.previous=lastItemReturned.previous;
lastItemReturned.previous.next=nextItem;
index--;
size--;
lastItemReturned = nextItem.previous;

}

@Override
public void set(E node) {
if (lastItemReturned == null) {
throw new IllegalStateException();
}
lastItemReturned.data = node;
}

} //end of iterator class

}

我的测试课

import CircularList.CircleIter;

public class CircularListTest {
public static void main(String[] args) {
CircularList<Integer> intList = new CircularList<Integer>();

CircleIter<Integer> iter= intList.CircleIter<Integer>();
iter.add(5);


}
}

最佳答案

如果您想创建 CircularList.CircleIter 的实例类你应该使用运算符“new”。
CircularList.CircleIter是 CircularList 类的内部类(非静态嵌套类),因此为了创建它的新实例,您应该提供包含类的实例 special syntax :
CircularList<Integer>.CircleIter iter = intList.new CircleIter();
通常集合会公开用于创建迭代器的特殊方法(例如 List 中的 iterator() 方法),以向消费者隐藏此语法。
正如 Alex Sou 之前提到的,只有封闭类在您的定义中被参数化。

关于java - 循环链表和迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35332075/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com