Java Comparator syntax works, but why?

This question already has an answer here:

  • Java inner class and static nested class 23 answers

  • SomeClass.PrioritizedPendingListComparator is a class. You need an instance of it so you have to use new

    When you define public static class the static means it doesn't implicitly have a reference to the outer class, but you still have to create it in the normal way.

    One way to avoid new is to use an enum .

    public enum PrioritizedPendingListComparator implements Comparator<SomeClass> {
        INSTANCE;
    
        @Override
        public int compare(SomeClass o1, SomeClass o2) {
        ...
        }
    

    later

     Collections.sort(pendingList, SomeClass.PrioritizedPendingListComparator.INSTANCE);
    
    链接地址: http://www.djcxy.com/p/92024.html

    上一篇: 有效的Java:将类作为私有嵌套类(第22项)

    下一篇: Java比较器语法的作品,但为什么?