简体   繁体   中英

Java Implementing Comparable

I am trying to overwrite the compareTo in Java such that it works as follows. There will be two string arrays containing k strings each. The compareTo method will go through the words in order, comparing the kth element of each array. The arrays will then be sorted thusly. The code I have currently is as follows, but it does not work properly.

I need a return statement outside the for-loop. I'm not sure what this return statement should return, since one of the for-loop return statements will always be reached.

Also, am I using continue correctly here?

public int compareTo(WordNgram wg) {
    for (int k = 0; k < (this.myWords).length; k++) {
        String temp1 = (this.myWords)[k];
        String temp2 = (wg.myWords)[k];
        int last = temp1.compareTo(temp2);
        if (last == 0) {
            continue;
        } else {
            return last;
        }
    }
}

您要在同一位置比较两个字符串:

int last = temp1.compare(temp2);

Java compiler mandates all the end points must have a return statement. In your case you must return 0 at end so when both arrays contain completely equal strings the caller will know they are equal.

You should start listening to your compiler, because after looking at your code for 1 minute, I spotted two undefined states: this.myWords.length is 0 and the two words are equal.

Also, I personally find it very difficult to handle multiple method exit points with all possibilities for input considered and rather insert a single returning statement which makes debugging easier and the results more predictable. In your case for example, I would collect the results of compareTo in a collection if they differ from 0 so that after the for-loop has finished, you could decide at the state of this collection if 0 (empty collection) or the first value in the collection could be returned. I like this more formal approach, because it enforces you to think set-like as in "Give me all comparing results where compareTo results in anything else but 0 . If this list is empty, the comparing result is 0 , otherwise it is the first element of the list."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM