Trie迭代器hasNext()和空指针

时间:2014-04-15 18:12:59

标签: java iterator trie

我试图实现我的迭代器并且空指针一直显示出来。我试图为一系列字符串实现迭代器类,以便我可以通过trie找到潜在的单词并从中创建组。不幸的是,我无法让这个迭代器正常工作。谁能发现这个?

public class TrieIteratorMain {

    /**
     * @param args
     *            Unused
     */
    public static void main(String[] args) {
        String[] words = { "cat", "mouse", "ball", "dog", "balloon", "fish" };
        Trie wordsTrie = new Trie();

        // copy all words into trie
        for (String word : words) {
            System.out.println("adding " + word);
            wordsTrie.addWord(word);
        }

        System.out.println();

        Iterator<String> iter = wordsTrie.iterator();
        while (iter.hasNext()) { /* null pointer */
            String word = iter.next();
            System.out.println("Got word: " + word);
            if (word.equals("dog"))
                iter.remove();
        }

        System.out.println();

        for (String word : wordsTrie) {
            System.out.println("Got word: " + word);
        }
    }
}

另一个班级

import java.util.Iterator;
import java.util.NoSuchElementException;

public class TrieIterator implements Iterator<String> {

    private Iterator<String> iter;

    public TrieIterator(Iterator<String> iter) {
        this.iter = iter;
    }

    public boolean hasNext() {
        return this.iter.hasNext();
    }

    public String next() {
        // TODO
        if (! hasNext())   throw new NoSuchElementException();
        String next = this.iter.next();
        return next;
    }

    public void remove() {
        // TODO
    }
}

更新:添加了TRIE课程 - 虽然看起来我没有保存我的上次编辑。我将继续处理,然后再次更新。所以这很可能一直是我的错误。

非常抱歉。在看了几个小时的代码后傻了!

import java.util.Iterator;

public class Trie implements Iterable<String> {
public Trie() {
    // TODO
}

/**
 * This method adds a word to the Trie
 * 
 * @param s
 *            - word to add to the Trie
 */
public void addWord(String s) {
    // TODO
}

/**
 * Returns the root node of the Trie.
 * 
 * @return The root node of the Trie
 */
public TrieNode root() {
    // TODO
    return null;
}

/**
 * This method returns an iterator for the trie, as required by the Iterable
 * interface.
 * 
 * @return and iterator for the trie.
 */
public Iterator<String> iterator() {
    // TODO
    return null;
}

/**
 * This method removes all entries from the trie using an iterator.
 */
public void clear() {
    Iterator<String> iter = iterator();
    while (iter.hasNext()) {
        iter.next();
        iter.remove();
    }
}

}

1 个答案:

答案 0 :(得分:0)

我不确定你要在这里做什么,但这里是你的空指针异常原因:

/**
 * This method returns an iterator for the trie, as required by the Iterable
 * interface.
 * 
 * @return and iterator for the trie.
 */
public Iterator<String> iterator() {
    // TODO
    return null;
}

您返回null,因此毫无疑问您在trie中访问此方法的尝试将返回null并在您尝试访问该空引用时导致NPE