Search code examples
javacompareto

can return a compareTo different result in different situations


i have a big doubt, i have for example a list of name and a value that could be the same for different names, when i do a compareTo it would return the list order by the number. But my questions is if i execute the app in order computer with the same list, will be returned the same list?

Deppends compareTo to the computer where you execute?

I know that the solution if to implement a compareTo where you use other param in addition to do the order, but i would like if in any case with tha same list the return list it will be different.


Solution

  • I'm not sure if I understand your question. In the case where you have the same value for two items, the compareTo will return 0 (in this case because this "number" is the same). This function, compareTo, only defines the order in which the algorithm should sort the items, and is up to the sorting algorithm to decide which one will be first. If you use the same algorithm, with exactly the same list, the output should be the same, at least for most commons algorithms, because they are not random. But if you change the list or the algorithm, the result can be completely different.

    So, to avoid that, you can reimplement the comapreTo function to compare a second value, in case the first one is the same. For example, if you have 2 num: n1 and n2 that matches 2 strings s1 and s2, you should do:

    int comparison = n1.compareTo(n2);
    if (comparison == 0){
        return s1.compareTo (s2));
    }
    

    Of course, you still have the problem when both n1==n2 and s1==s2. But then maybe this is not a problem because if all the data is the same, the objects are equivalent, right? ;)

    I hope it helps