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

我只是一个虾纸丫 提交于 2019-11-27 21:41:42
polygenelubricants

One is for conciseness for what should be a common case (Effective Java 2nd Edition, Item 12: Consider implementing Comparable). The other, as you noted, is for flexibility and general-purposeness.

Related questions

It depends who controls the ordering. If the ordering of an object is an implementation detail of the object, the Comparable is more appropriate. If the ordering of the objects is controlled by the caller, then Comparator is more appropriate.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!