我为哈希表编写的Iterator<String> elements()
方法没有通过我给出的其中一个测试。这有什么问题?
public Iterator<String> elements(){
Iterator<String> it = new Iterator<String>(){
private int i = 0;
@Override
public boolean hasNext() {
return i < hashTable.length && hashTable[i] != null; //if i set this to always return true i get a null.pointer.exception.
// then an error on line 115 which is the line for next().
}
@Override
public String next() {
i++;
return hashTable[i].getKey();
}
};
return it;
}
以下是测试:
/** Test 8: Get iterator over all keys
* @throws MapException */
private static boolean test8() throws MapException {
boolean result = true;
String s;
StringHashCode sHC = new StringHashCode();
float maxLF = (float) 0.5;
HashTableMap h = new HashTableMap(sHC,maxLF);
try
{
for (int k = 0; k < 100; k++)
{
s = (new Integer(k)).toString();
h.insert("R"+s+"C"+s);
}
for (int k = 10; k < 30; k++)
{
s = (new Integer(k)).toString();
h.remove("R"+s+"C"+s);
}
}
catch(MapException e)
{
result = false;
}
Iterator<String> it = h.elements();
int count = 0;
while (it.hasNext()){
count++;
it.next();
}
if ( h.numberOfElements() != 80) {
result = false;
}
if ( count != 80) {
result = false; // if i comment out this line the test passes so i am assuming the iterator is the problem.
}
return result;
}
我确信我的Iterator<String> elements()
方法的代码是正确的,但我可能错过了一个简单的错误,因为我已经看了这么久。