java - 使用 compareTo(String) 得到错误说 undefined for the type String

标签 java string tree compareto

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/

相关文章:

java - Linux 中的 WLS 12.1.3 - 消息未被消费者收听

php - 在 PHP 中从数据库中删除 TinyMCE 格式

java - 如何从数组或列表中删除两个元素的序列?

c++拆分字符串并获取空格之后的部分

java - struts2使用什么算法来生成随机 token ?

java - do while 循环中正确循环的问题 - Java

data-structures - 如果您知道二叉树的节点数,如何找到二叉树的最小高度?

c# - 如何使用 ObjectListView 或 TreeListView 显示树结构

java - 当我尝试计算 2 的 n 次幂时,当 n 大于 30 时,我得到 0,我该如何修复它?

javascript - 获取 Fuelux 树中文件夹的 ID 或名称