Good day.

There is an example of a method that sorts a list, in which the static methods sort() and reverseOrder() . They are written with reference to the Collections class:

 Collections.sort(copy, Collections.reverseOrder()); 

If the sort() method is found in many classes and you cannot do without a specifying reference to Collections , then the reverseOrder() method is presented only in one instance. Why, in this case, write:

 Collections.sort(copy, reverseOrder()); 

will be wrong?

Thank you.

  • You call the sort () method in the second case in which class? - SlandShow
  • string Collections.sort(copy, reverseOrder()); is in which class code? What is a contact? - Igor
  • one moment, lay out for clarity gh .. - Dmitry08
  • goo.gl/b0P0Mk , line 453 .. - Dmitry08
  • The original class in the second case is the same, the context does not change. - Dmitry08

2 answers 2

This problem is solved by static importing:

import static java.util.Collections.reverseOrder;

Otherwise, it is necessary during compilation to bypass all the classes in the classpath and check for the presence of this function there.

    Regarding your question, I see several problems that the compiler may stumble upon:

    • first, it is a search across all classes (a rather heavy task, considering how many times it will have to be performed),
    • secondly, this is the destruction of the scope (imagine, you declared a variable, which is called the same as one of the methods in any of the classes, how can the compiler do then?).
    • In addition, you can simply be sealed up and call a class method that was not even suspected ...

    I think you can think of many problems, at a time when the benefits are minimal (I would even say that the harm of such features would have been brought in much more).

    • Looks like I figured it out. This problem is solved by static importing: 'import static java.util.Collections.reverseOrder;' Anyway, thank you very much. - Dmitry08
    • @ Dmitry08 you can issue your decision as an answer to your own question. - hunter
    • Probably worth it, yes. - Dmitry08
    • one
      It fits. The enSO is full of such questions. - andreycha
    • one
      enSO I gave an example, because the rules are a little more stringent than ours. And if it is allowed there, then even more so. As for the subject matter, the answers to such questions (if they are available) are always unambiguous and quite acceptable in terms of volume. And it is all the more useful to answer the questions in the spirit of "My code does not compile, what's the matter?". However, let's discuss this on the meta : meta.ru.stackoverflow.com/q/3522/106 - andreycha