【发布时间】:2018-09-10 08:16:30
【问题描述】:
我正在使用标准实现中的一些方法创建 LinkedList 的实现。在将迭代器功能添加到我的 LinkedList 时,我遇到了一个问题。
现在我可以添加一些元素,然后像这样
class testList {
public static void main(String[] args){
MyLinkedList<String> list = new MyLinkedList<String>();
list.add("Element 0");
list.add("Element 1");
list.add("Element 2");
Iterator<String> iter = list.iterator();
System.out.println(iter.next());
System.out.println(iter.next());
System.out.println(iter.next());
for (String s : list){
System.out.println(s);
}
}
}
除了最后一部分外,一切正常,当我试图编译它时,我收到一个错误提示错误:for-each not applicable to expression type for (String s : list)
在实施过程中我是否忽略了一些明显的东西?
这是我的其余代码,我正在为 Iterable 和 List 使用自定义接口
interface List<T> extends Iterable<T> {
public int size();
public void add(int pos, T x);
public void add(T x);
}
interface Iterator<T> {
boolean hasNext();
T next();
}
interface Iterable<T> {
Iterator<T> iterator();
}
这是代码的主要部分
import java.util.* ;
class MyLinkedList<T> implements List<T> {
private Node<T> head;
private Node<T> tail;
private int currentSize;
//constructor for class
public MyLinkedList(){
this.head = null;
this.tail = null;
this.currentSize = 0;
}
//Node class used to hold the information, and link to each other
public class Node<E> {
private E data;
private Node<E> next;
//constructor for node class
public Node(E data, Node<E> next){
this.data = data;
this.next = next;
}
public E getData(){
return this.data;
}
public void setData(E newData){
this.data = newData;
}
public Node<E> getNext(){
return this.next;
}
public void setNext(Node<E> newNext){
this.next = newNext;
}
}
class LinkedListIterator implements Iterator<T>{
private Node<T> current;
public LinkedListIterator(){
current = head;
}
public T next(){
if (current == null){
throw new NoSuchElementException();
}
T temp = current.getData();
current = current.getNext();
return temp;
}
public boolean hasNext(){
return current != null;
}
}
public Iterator<T> iterator(){
return new LinkedListIterator();
}
public int size(){
return this.currentSize;
}
public boolean isEmpty(){
return this.size() == 0;
}
public void add(int pos, T x){
if(pos < 0 || pos > size()){
throw new IndexOutOfBoundsException();
}
if(pos == size()){
add(x);
return;
}
if (pos == 0){
head = new Node(x, head);
}else{
Node<T> current = head;
for(int j = 0; j < pos-1; j++){
current = current.getNext();
}
current.setNext(new Node(x, current.getNext()));
}
currentSize++;
}
public void add(T x){
if(isEmpty()){
head = new Node(x, null);
tail = head;
}else{
tail.setNext(new Node(x, null));
tail = tail.getNext();
}
currentSize++;
}
}
【问题讨论】:
标签: java iterator singly-linked-list iterable