使用集合对列表进行排序会导致错误

时间:2015-03-30 10:58:30

标签: java arraylist collections lis

我有一个MatOfDMAtch类型的对象,我转换为一个列表,我想使用集合对它进行排序,但是当我运行代码时,我收到以下错误。

请让我知道为什么我会收到这些错误以及如何解决。

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));
    }*/
}

错误

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)

更新

现在我使用了比较器接口,但正如您在注释掉的行中的acode中看到的那样,我不能使用.compareTo()方法! 怎么用?

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??
    }
};

3 个答案:

答案 0 :(得分:1)

您的DMatch类必须实现Comparable接口,或者必须使用可以比较DMatch对象的适当比较器调用Collections.sort(...)。

答案 1 :(得分:1)

您必须实现这样的自定义Comparator(通过getter更改getYourValueToCompare()):

Collections.sort(dMatchList, new Comparator<DMatch>() {
    public int compare(DMatch a1, DMatch a2) {
        return a1.getYourValueToCompare().compareTo(a2.getYourValueToCompare());
    }
});

注意:请务必为DMatch课程实施equals method,否则您将无法看到任何排序!!

答案 2 :(得分:0)

org.opencv.features2d.DMatch未实现接口java.lang.Comparable。因此默认情况下无法比较。您必须自己编写Comparator

并致电java.util.Collections.sort(list, new MyDMatchComparator());

public class MyDMatchComparator implements Comparator<DMatch>{

    @Override
    public int compare(DMatcho1, DMatch o2) {
       //compare logic
    }
}