java StringTokenizer - nextToken可以返回null吗?

时间:2011-01-23 09:47:57

标签: java stringtokenizer

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

由于

2 个答案:

答案 0 :(得分:5)

如果tokenizer的字符串中没有更多的标记,

nextToken()会抛出NoSuchElementException;所以我会说它不会返回null。

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

答案 1 :(得分: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;
    }