为不可比较列表实现自然顺序比较器
我正在为 ArrayList
的克隆实现 List
接口。我正在尝试实现 sort
(来源): 我不确定如何实现比较器为空的情况。我的 ArrayList 没有扩展 Comparable ,因为我希望能够在列表中存储不可比较的对象。我尝试对 sort
方法使用以下内容:
public void sort(Comparator<? super E> c){
if(c == null){
// Use ascending order
class ascComparator<T extends Comparable<? super T>> implements Comparator<T> {
public int compare(T a, T b) {
return a.compareTo(b);
}
}
c = new ascComparator<E>();
}
// Implementation of merge sort goes here
}
这预计会产生错误,因为 E
不会扩展 Comparable
。在上面的文档中,指出“如果...为 null,则此列表中的所有元素都必须实现 Comparable 接口”。如何检查列表中的对象是否实现了 Comparable
以及如何使用 compareTo
而不会出现错误?有没有更好的方法来做到这一点?
I'm implementing the List
interface for a clone of ArrayList
. I'm trying to implement sort
(source):
I'm not sure how to implement the case where the comparator is null. My ArrayList
does not extend Comparable
because I want to be able to store non-comparable objects in the list. I've tried using the following for the sort
method:
public void sort(Comparator<? super E> c){
if(c == null){
// Use ascending order
class ascComparator<T extends Comparable<? super T>> implements Comparator<T> {
public int compare(T a, T b) {
return a.compareTo(b);
}
}
c = new ascComparator<E>();
}
// Implementation of merge sort goes here
}
This expectedly gives an error as E
does not extend Comparable
. In the above documentation it is stated "if ... is null then all elements in this list must implement the Comparable interface". How do I check that the objects in the list implement Comparable
and how do I then use compareTo
without getting an error? Is there just a better way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要了解 ArrayList 的作用,请尝试:
您的比较器必须假设列表中的对象是可比较的,这是它能做的最好的事情:
如果您列表中的项目不具有
可比性
。To see what
ArrayList
does, try:Your comparator must just assume that the objects in the list are Comparable, that's the best it can do:
Which will throw a
ClasscastException
if the items in your list are notComparable
.你只需要进行不安全的转换。确实没有办法解决这个问题。
You just have to do the unsafe cast. There's really no way around it.