简体   繁体   English

Java实现可比

[英]Java Implementing Comparable

I am trying to overwrite the compareTo in Java such that it works as follows. 我试图覆盖Java中的compareTo,使其工作如下。 There will be two string arrays containing k strings each. 将有两个字符串数组,每个数组包含k个字符串。 The compareTo method will go through the words in order, comparing the kth element of each array. compareTo方法将按顺序遍历单词,比较每个数组的第k个元素。 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. 我需要在for循环之外的return语句。 I'm not sure what this return statement should return, since one of the for-loop return statements will always be reached. 我不确定该return语句应该返回什么,因为总是会到达for循环return语句之一。

Also, am I using continue correctly here? 另外,我是否在此处正确continue使用?

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. Java编译器要求所有端点必须具有return语句。 In your case you must return 0 at end so when both arrays contain completely equal strings the caller will know they are equal. 在您的情况下,您必须在末尾返回0,因此,当两个数组都包含完全相等的字符串时,调用者将知道它们相等。

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. 您应该开始聆听编译器,因为在看了1分钟的代码之后,我发现了两个未定义的状态: this.myWords.length0 ,两个词相等。

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. 以您的情况为例,如果比较值与0不同,我将在集合中收集compareTo的结果,以便在for循环完成后,您可以确定此集合的状态是0 (空集合)还是第一个值在集合中可以返回。 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." 我喜欢这种更正式的方法,因为它可以使您像“将所有比较结果都给我,其中compareTo导致除0其他结果一样”进行思考。如果此列表为空,则比较结果为0 ,否则为第一个列表中的元素。”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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