Comparable与Comparator的区别
Comparable和Comparator都是用来实现集合中元素的比较、排序的。
Comparable是在集合内部定义的方法实现的排序,位于java.util下。
Comparator是在集合外部实现的排序,位于java.lang下。
Comparable是一个对象本身就已经支持自比较所需要实现的接口,如String、Integer自己就实现了Comparable接口,可完成比较大小操作。自定义类要在加入list容器中后能够排序,也可以实现Comparable接口,在用Collections类的sort方法排序时若不指定Comparator,那就以自然顺序排序。所谓自然顺序就是实现Comparable接口设定的排序方式。
Comparator是一个专用的比较器,当这个对象不支持自比较或者自比较函数不能满足要求时,可写一个比较器来完成两个对象之间大小的比较。Comparator体现了一种策略模式(strategy design pattern),就是不改变对象自身,而用一个策略对象(strategy object)来改变它的行为。
总而言之Comparable是自已完成比较,Comparator是外部程序实现比较。
U2FsdGVkX1/suxoBioxge0P6tG85reZ4VIyHam8GoYD1P4enO0EQwz3jxiXl5e3j
6qHmEW7dBmPJdrdq0f+ALpg6gTvPhUBjYjCAfw4LGb6OBsSzL39NPuIx8FZMVzu7
L4WYivcvsdyTfVx9XmGc4djEXWyK9GDznHUzH/diI7afykaDXi1jsPWwO/hEBhO5
F7CyBVL4WNH/DTsfJJ3HOeCctZnuPpWHZy4YrYvPAt+ORTCCvv1WwsogJMeVq/Xe
noXXCqTKmz8OigIDHk6D4QvTYlYuz9sZqi9H8ak8Grl4mOQiU3zmcvZ+i0Gy4gdf
nyelYMEEmC8EoEB2zldFktDghMoS7mDNX4+0EZvuIxiIgWP0PsQxmub3RWSkY5xK
NUOrBEP7gCa0rcEebYTn3g1Wju0Syx1H/5GbyFKDs6LJ/8LPAo88jwDUfESRwbMC
hOsX8ySUuLR0mmJIURKqQtkymqQgPsaWtwpyuN0jabBYZclwaQoz8St/lNFHR8Kt
gIQA9GqXYKbKK62GPLGFaAhQhnOhpTVCxUj7Fx/CoR1rCsgrwthpGpOyW/bMeLg5
EslYwXMwIIXlV1NeuDO97r60mnVfrfRTK6qUeMLU5Mk1epFP+5YPUJjHNucDpf6R
R59dbODZKbq/v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