How to use the Comparator interface

后端 未结 5 2160
陌清茗
陌清茗 2020-12-29 09:32

I\'m new to java, and I\'m not really getting how to use the comparator interface. I have an ArrayList of Items in an Inventory class

5条回答
  •  南笙
    南笙 (楼主)
    2020-12-29 09:42

    You are mixing up the interfaces Comparator and Comparable.

    Comparator: http://docs.oracle.com/javase/6/docs/api/java/util/Comparator.html

    Comparable: http://docs.oracle.com/javase/6/docs/api/java/lang/Comparable.html

    The purpose of Comparator is a class (declared anonymously on the spot or otherwise) that can be passed to an operation that needs an ordering, and it defines the sort that will be used on the item. Comparator is to be used OUTSIDE of the class that needs sorting, if there is an alternative way you want to sort it by.

    The purpose of Comparable is to say that the class (that implements Comparable) has a natural ordering - and this is what it is. If your class that needs sorting has a natural ordering, then define it as Comparable. (A class that implements Comparable's sort order can still be overriden by a Comparator. On the other hand, if the class is not Comparable than also passing a Comparator is mandatory for ordering to be possible.)

提交回复
热议问题