我正在 Dart 中对一个简单的 MergeSort 进行泛化。
只是作为占位符,我想了一个 Node
的列表将为 List<T>
制作一个足够的包装器。由于 T 是一个对象,它本身没有compareTo、<、>、<= 等,因为它不是数字或字符串。
如何删除这些警告。
class Node<T> extends Comparable {
T _value;
Node(T value){
_value = value;
}
//.....
}
class MergeSort<T>{
list<Node<T>> _list;
MergeSort(List<Node<T>> list){
_list = list;
}
List<Node<T>> Sort( List<Node<T>> list ){
_list = list;
//.....
}
}
我遇到的问题是,在合并排序中,我需要比较节点,这已经足够了。我实现operator ==
等来处理这些情况,或 operator <
对于那些情况。自从我扩展了 Comparable 以来,我也有 compareTo
由于字符串。
我不确定如何适应传递给 Node、T 的类,并且我不知道是否有办法拥有它 expect
数字、字符串等
完整的类实现+可共享的dartpad:https://dartpad.dartlang.org/645157fb547da482fc2b
class Node<T> extends Comparable{
T _value;
Node(T item){
_value = item;
}
T getValue () => _value;
bool operator ==(other) => identical(this, other);
bool operator <( other){
if (other is! T){
return false;
}
//other is of same type, T.
if (_value < (other as Node<T>).getValue()){
return true;
}
return false;
}
bool operator <= (other){
return (this == other) || (this < other);
}
int compareTo (other){
if (this == other){
return 0;
}
if (this < other) {
return -1;
}
return 1;
}
}
也许拥有一个节点包装器太多了?我觉得我也许可以去掉 Node 类,只拥有一个 T 列表,但是当涉及到列表元素的比较时,问题就会被推到 MergeSort 中。
最佳答案
我想你正在寻找的是
class Node<T extends Comparable>
和
class MergeSort<T extends Comparable>{
但是Comparable
没有实现>
/<
。如果您想使用这些,您可以创建自己的父类(super class),并且需要实现该类。
关于algorithm - 通用排序函数接受 T,但要确保 T 是可比较的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35122891/