I was doing some Genericizing of a simple MergeSort in Dart.
Just to be a placeholder, i thought a List of Node
would make a sufficient wrapper to the List<T>
. Since T is an object, it doesnt natively have compareTo, <, >, <= etc because it isnt a num or a string.
How do i get these warnings removed.
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;
//.....
}
}
The issue i am getting at is that in the MergeSort, i need to compare nodes, which is fine enough. I implement operator ==
etc to handle those cases, or operator <
for those cases. I also have, since i extended Comparable, compareTo
since Strings.
I was not sure how to accommodate for the classes being passed into Node, T, and i didn't know if there was a way to have it expect
num, string, etc.
full class implementation + a shareable 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;
}
}
Maybe having a Node Wrapper is too much? I kinda feel like i might be able to strip away the Node class, and just have a List of T, but then the issue would be just pushed into the MergeSort when it comes to comparisons of the list elements.
I think what you are looking for is
class Node<T extends Comparable>
and
class MergeSort<T extends Comparable>{
but Comparable
doesn't implement the >
/ <
. If you want to use these you can create your own superclass that does and require this class to be implemented instead.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments