Why does the Java Collections Framework offer two different ways to sort?

后端 未结 3 1343
忘了有多久
忘了有多久 2020-12-05 22:12

If I have a list of elements I would like to sort, Java offers two ways to go about this.

For example, lets say I have a list of Movie objects and I’d like to sort

3条回答
  •  旧时难觅i
    2020-12-05 22:49

    I'm not sure I find it that odd. I have a list of things to sort that have a natural order like numbers. Do I really expect I have to tell the API how to compare numbers? I wouldn't look for a two-arg method, intuitively. Thus Comparable exists.

    But of course you can and should be able to define a different ordering, thus the other method. For example, even though numbers have a natural ordering, I may still want a different ordering: for example, order by value descending. Thus Comparator exists.

    And of course some things don't have a natural ordering like Fruit, but you might still wish to order a list of them. Thus Comparator, again.

提交回复
热议问题