通用排序函数接受 T,但要确保 T 具有可比性

Generic Sorting function accepts T, but want to ensure T is comparable

我在 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;
    //.....
  }
}

我遇到的问题是在 MergeSort 中,我需要比较节点,这已经足够了。我实施 operator == 等来处理这些情况,或实施 operator < 来处理这些情况。我也有,因为我扩展了 Comparable,compareTo 因为 Strings.

我不确定如何适应 classes 被传递到 Node, T,我不知道是否有办法让它 expect num, string,等等

完整的 class 实现 + 可共享的飞镖板: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;  
  }
}

也许节点包装器太多了?我有点觉得我可以去掉节点 class,只得到一个 T 列表,但是当涉及到列表元素的比较时,这个问题就会被推到 MergeSort 中。

我想你要找的是

class Node<T extends Comparable>

class MergeSort<T extends Comparable>{

但是 Comparable 没有实现 > / <。如果你想使用这些,你可以创建你自己的 superclass 并要求实现这个 class 。