Collections.binarySearch(Java)中的下划线(_)问题

时间:2010-04-26 14:44:51

标签: java list collections binary-search

问题:

我正在使用Java Tutorials™源代码。这是source code.

我试过了:

--following with another section of sorted words--
words.add("count");
words.add("cvs");
words.add("dce"); 
words.add("depth");
--following with another section of sorted words--

它完美无缺。但是,当我使用它时:

--just a section of sorted words--
words.add("count");
words.add("cvs");
words.add("dce_iface"); 
words.add("dce_opnum");
words.add("dce_stub_data");
words.add("depth");
--following with another section of sorted words--

当我输入dce_iface时,它会显示dce,但当我输入_然后跟随os时,它会显示其他内容,例如{ {1}}其中偏移量来自列表中某处的dce_offset

我该怎么做才能解决这个问题?提前谢谢。

3 个答案:

答案 0 :(得分:1)

这可能是因为代码中的这些行:

for (w = pos; w >= 0; w--) {
    if (! Character.isLetter(content.charAt(w))) {
        break;
    }
}

_不是字母字符,因此它以与空格相同的方式对待它。您可以尝试将条件更改为:

char c = content.charAt(w);
if (! (Character.isLetter(c) || c == '_')) {

答案 1 :(得分:1)

我猜你必须在这里添加下划线作为“字母”

        // Find where the word starts
        int w;
        for (w = pos; w >= 0; w--) {
            if (!Character.isLetter(content.charAt(w))) {
                break;
            }
        }

答案 2 :(得分:1)

这与insertUpdate()中的此部分有关:

// Find where the word starts
int w;
for (w = pos; w >= 0; w--) {
    if (! Character.isLetter(content.charAt(w))) {
        break;
    }
}

具体来说,Character.isLetter()对下划线字符返回false。这意味着该单词在下划线位置后开始。

要解决此问题,您需要修改if语句,以允许在单词中使用任何非字母字符。您可以明确检查“_”或使用Chacter.isWhiteSpace()包含所有不是空格,制表符或换行符的字符。