سؤال

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);
   }

I'm using Eclipse, and the red underline says

"The method compareTo(String) is undefined for the type String"

. How can I fix this?

treemap code.. about the node.

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;
   }

This is what shows when I use 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

I tried to replace newWord with a string "hello", then the underline disappeared. but how can I fix this?

هل كانت مفيدة؟

المحلول

Here "String" is not java.lang.String, it is a type parameter declared with the definition of the treemap class. You are working in a generic class, and String is a type variable of this class.

In other words, this :

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;
   }

...Has the same meaning that this :

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;
   }

If you want T to extend String and U to extend Integer, then you should define your class like that :

class treemap<T extends String, U extends Integer> {

نصائح أخرى

At first glance, the parameter 'cur.word' is causing this. Try replacing it temporarily with "test" to see if the compilation error goes.

I think cur.word isn't accessible

You might want to use equal(). Here is an example:

String one = "Dog";
String two = "dog";
if (one.equalsIgnoreCase(two)) {
  System.out.println("Words are the same");
} else {
  System.out.println("Words are not the same");
}

if (one.equals(two)) {
    System.out.println("Words are the same- Caste Sensative");
} else {
    System.out.println("Words are not the same -- Caste Sensative ");
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top