Are comparators new or injectable?

See the question in the title! Would you "introduce" or rather a "new" comparator? Would you do this if the order of the elements is specified in the specification and probably won't change?

+5
source share
4 answers

The question "Should I introduce this dependency?" really "should the reference object know the nature of this dependency?". Er, only denied.

If your class is FastestPonyFinder, and it needs to be sorted List<Pony>by speed, then I would say that it should know about the comparator. The comparator should compare by speed, sorting the fastest to the list title; no other comparator is suitable for operation. The object must create a comparator, just as it did List.

If your class is BestPonyFinder, then a comparator should probably be introduced into it, because the definition of what constitutes the “best” is separable from the definition of how to find the pony that meets it. This will make your code easier to test and easier to change in the future.

+3
source

The thing about comparators is that they are cheap. They do not often have fields, and if they do, there are not many.

, . inline - ?

+1

, , " ". . , : .

0

Comparator, , . , , .

0

All Articles