我這個簡單的代碼迭代器仿製藥,不能宣佈不匹配的類型(也許鑄造發行)的迭代器
public String toString() {
**Iterator it = list.iterator();**
String s;
while(it.hasNext()){
s = s + " " + Integer.toString(it.next());
}
System.out.println(s);
// IMPLEMENT THIS METHOD VIA AN ITERATOR
// MAKE SURE THE OUTPUT PRODUCED BY THE METHOD
// DISPLAYS THE LEAST SIGNIFICANT BIT TO THE RIGHT.
}
在用星號線,我得到以下編譯錯誤。
Error: incompatible types
required: Iterator
found: java.util.Iterator<java.lang.Integer>
我已經試過了,
**Iterator<Integer> it = list.iterator();**
我得到的,Error: type Iterator does not take parameters
編輯*
我忘了提,我有我自己的實現的接口方法。
/*
* Inner class to implement the iterator for the <code>BitList</code>.
*/
private class BitListIterator implements Iterator {
/*
* A reference to the current <code>Node</code> in the iterator.
*/
private Node current = null;
/*
* The expected modification count variable.
* Needed for the "fast-fail" implementation of the iterator.
*/
private int expectedModCount = modCount;
/*
* Advances the iterator to the next element in the list.
*/
public int next() {
checkValid();
if (current == null) {
current = first ;
} else {
current = current.next ; // move the cursor forward
}
if (current == null)
throw new NoSuchElementException() ;
return current.value ;
}
/**
* Inserts a new <code>int</code> value immediately before the next element that would be returned by <code>next()</code>.
*/
public void add(int newElement) {
Node newNode;
if (current == null) {
first = new Node(newElement, first);
current = first;
} else {
current.next = new Node(newElement, current.next);
current = current.next;
}
modCount++ ;
expectedModCount++ ;
}
/**
* Indicates whether there is a next element in the list being traversed or not.
*/
public boolean hasNext() {
return ((current == null) && (first != null)) ||
((current != null) && (current.next !=null));
}
/**
* Checks whether this iterator remains valid, i.e. no concurrent modifications have been made on the list.
*/
private void checkValid() {
if (expectedModCount != modCount)
throw new ConcurrentModificationException();
}
} // end of BitListIterator class
因此,如果導入的包我收到以下錯誤
Error: BitList.BitListIterator is not abstract and does not override abstract method remove() in java.util.Iterator
Error: next() in BitList.BitListIterator cannot implement next() in java.util.Iterator
return type int is not compatible with java.lang.Object
我有JDK 1.7和它的使用。
任何想法肯定會有所幫助。
謝謝
Mjall2
編譯器是正確的。你還沒有實現'remove()',你的next()的定義與'Iterator'接口中定義的'next()'不兼容。如果您要使用迭代器類,則需要解決這些問題。 – QuantumMechanic 2012-04-11 00:47:12
「list」是什麼類型?它是'BitList'嗎?當你調用'iterator()'時,你想讓你的'BitList'類返回你的'BitListIterator'實現嗎? – QuantumMechanic 2012-04-11 00:49:35
確保您沒有在同一目錄中名爲Iterator.class的類文件 – newacct 2012-04-11 02:05:56