开发者

Creating compareTo method in java with one parameter

I have a question about making a compareTo function in Java.

In Java, we have the String.compareTo(String) method.

However, I need to make a compareTo function with only only parameter, like: compareTo(String).

I assume that I need to use this to hold another string.

For example:

public static boolean compareTo(String word)
{

  private string this.word = word;

   if(word.equals(this.word))
   {
       return true;

    } 
   else
  {
    return false;
  }

}

Is this the right idea?

Do I need to create get and set functions to hold first word to compare with second word?

Thank开发者_开发问答s


To compare two objects, you need to implement the Comparable interface. As part of the implementation, you will write your own compareTo() method. This method compares your current object with the object being passed.

public MyObj implements Comparable<MyObj> {

        ...
        public int compareTo(MyObj anObj) {
               // if your obj greater than anObj, return 1
               // if equal, return 0
               // else return -1
        }
}

Further down in your code, you can then do --

  `MyObj anObj = new MyObj();
   MyObj anObj1 = new MyObj();
   // anObj.compareTo(anObj1) ....

   // This will also be useful if you have a collection of MyObjs.
   Collections.sort(arrayListOfMyObjs);


That's not the right idea in many ways...

  • You cannot use this in a static function.
  • You cannot add a visibility declaration to a local variable of a function.
  • There is no string but String in Java.
  • You make this.word equals to word then check if they are equal...
  • You don't need to do if/else to return a boolean: just do return x.equals(y); (not necessarily wrong, but that's a personal pet peeve...).
  • compareTo, the classical one, isn't equals, but returns -1, 0 or 1 depending if one object is lower, equals or higher than the other.

Revise your lessons... :-)


In your code, the method compareTo is static, so you can not use "this." I suggest you'd better NOT make compareTo method static.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜