i have an object of type MatOfDMAtch and i converted to a list and i want to sort it as shown below using Collections, but when i run the code i receive the below errors.
please let me know why i am receiving these errors and how to solve it.
CODE:
List dMatchList = matDMatch.toList();
System.out.println("dMatchList.size(): " + dMatchList.size());
sortMAtches(0, 100, dMatchList);
}
private static void sortMAtches(double minDist, double maxDist, List list) {
// TODO Auto-generated method stub
java.util.Collections.sort(list);
/*for (int i = 0; i < list.size(); i++) {
System.out.println("lsit[" + i + "] = " + list.get(i));
}*/
}
ERRORS:
Exception in thread "main" java.lang.ClassCastException: org.opencv.features2d.DMatch cannot be cast to java.lang.Comparable
at java.util.ComparableTimSort.countRunAndMakeAscending(Unknown Source)
at java.util.ComparableTimSort.sort(Unknown Source)
at java.util.Arrays.sort(Unknown Source)
at java.util.Arrays.sort(Unknown Source)
at java.util.Arrays$ArrayList.sort(Unknown Source)
at java.util.Collections.sort(Unknown Source)
at test.FeaturesMatch.sortMAtches(FeaturesMatch.java:96)
at test.FeaturesMatch.main(FeaturesMatch.java:91)
UPDATE:
now i used the comparator interface, but as you see in the acode below at the commented out line, i cant use .compareTo() method! how to use it?
List<DMatch> dMatchList = matDMatch.toList();
DMatch[] dMatArray = matDMatch.toArray();
System.out.println("dMatchArray.length(): " + dMatArray.length);
System.out.println("dMatchList.size(): " + dMatchList.size());
java.util.Collections.sort(dMatchList, compa);
}
static Comparator<DMatch> compa = new Comparator<DMatch>() {
public int compare(DMatch arg0, DMatch arg1) {
// TODO Auto-generated method stub
return arg0.distance.???; //compareTo() does not exist??
}
};
You must implement a custom Comparator like this (change getYourValueToCompare()
by your getter):
Collections.sort(dMatchList, new Comparator<DMatch>() {
public int compare(DMatch a1, DMatch a2) {
return a1.getYourValueToCompare().compareTo(a2.getYourValueToCompare());
}
});
NOTE: Remember to implement equals method for DMatch
class or you won't see any sorting!!