public node add(String newWord, int ln, node cur) {
if (cur == null) {
return new node(newWord,ln);
}
int result=newWord.compareTo(cur.word); //compareTo is underlined suggesting an error
if ( result == 0) ;
else if (result < 0) {
cur.left = add(newWord,ln, cur.left);
} else {
cur.right = add(newWord,ln, cur.right);
}
return cur;
}
public void add(String word, int ln) {
root = add(word,ln, root);
}
我正在使用 Eclipse,红色下划线表示
"The method compareTo(String) is undefined for the type String"
.我该如何解决这个问题?
TreeMap 代码..关于节点。
class treemap<String, Integer> {
private class node {
String word;
int line;
node left;
node right;
node(String wd, int ln){
word=wd;
line=ln;
}
}
private node root;
public treemap(){
root=null;
}
这是我使用 javac 时显示的内容:
error: cannot find symbol
int result=newWord.compareTo("test");
symbol: method compareTo
location: variable newWord of type String
where String is a type-variable:
String extends Object declared in class treemap
我尝试用字符串“hello”替换 newWord,然后下划线消失了。但我该如何解决这个问题?
最佳答案
这里的“String”不是java.lang.String
,它是用treemap类的定义声明的类型参数。
您正在一个泛型类中工作,String
是此类的类型变量。
换句话说,这:
class treemap<String, Integer> {
private class node {
String word;
int line;
node left;
node right;
node(String wd, int ln){
word=wd;
line=ln;
}
}
private node root;
public treemap(){
root=null;
}
...与此具有相同的含义:
class treemap<T, U> {
private class node {
T word;
int line;
node left;
node right;
node(T wd, int ln){
word=wd;
line=ln;
}
}
private node root;
public treemap(){
root=null;
}
如果你希望 T 扩展 String 和 U 扩展 Integer,那么你应该这样定义你的类:
class treemap<T extends String, U extends Integer> {
关于java - 使用 compareTo(String) 得到错误说 undefined for the type String,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21839989/