1

是否存在 StringTokenizer.nextToken 将返回 null 的情况?我正在尝试在我的代码中调试 NullPointerException,到目前为止,我发现的唯一可能性是从 nextToken() 返回的字符串返回 null。有这种可能吗?在 java 文档中没有找到任何内容。

谢谢

4

2 回答 2

5

如果标记器的字符串中没有更多标记,则 nextToken() 将抛出 NoSuchElementException;所以我会说它不返回null。

http://download.oracle.com/javase/1.4.2/docs/api/java/util/StringTokenizer.html#nextToken ()

于 2011-01-23T09:50:19.357 回答
1

我认为它可以抛出 NullPointerException。

检查 nextToken() 的代码,

public String nextToken() {
        /*
         * If next position already computed in hasMoreElements() and
         * delimiters have changed between the computation and this invocation,
         * then use the computed value.
         */

        currentPosition = (newPosition >= 0 && !delimsChanged) ?
            newPosition : skipDelimiters(currentPosition);

        /* Reset these anyway */
        delimsChanged = false;
        newPosition = -1;

        if (currentPosition >= maxPosition)
            throw new NoSuchElementException();
        int start = currentPosition;
        currentPosition = scanToken(currentPosition);
        return str.substring(start, currentPosition);
    }

在这里,方法 skipDelimiters() 的调用可能会抛出 NullPointerException。

private int skipDelimiters(int startPos) {
        if (delimiters == null)
            throw new NullPointerException();

        int position = startPos;
        while (!retDelims && position < maxPosition) {
            if (!hasSurrogates) {
                char c = str.charAt(position);
                if ((c > maxDelimCodePoint) || (delimiters.indexOf(c) < 0))
                    break;
                position++;
            } else {
                int c = str.codePointAt(position);
                if ((c > maxDelimCodePoint) || !isDelimiter(c)) {
                    break;
                }
                position += Character.charCount(c);
            }
        }
        return position;
    }
于 2011-01-23T10:03:30.130 回答