سؤال

As a begginer in Java, I'm getting the following compile error trying to assign a custom comparator to a set:

The type mycode.pointComparator is not generic; it cannot be parameterized with arguments

here is my code:

Set<Point3d> cornerPoints = new TreeSet<Point3d>(new pointComparator<Point3d>());

class pointComparator implements Comparator<Point3d> {

        @Override
        public int compare(Point3d o1, Point3d o2) {
            if(!o1.equals(o2)){
                return -1;
            }
            return 0;
        }
    }

I'm importing Java.util. packages

Update: removing <Point3d> parameter results in this error:

No enclosing instance of type mycode is accessible. Must qualify the allocation with an enclosing instance of type mycode (e.g. x.new A() where x is an instance of mycode).

هل كانت مفيدة؟

المحلول

This works:

public static void main(String[] args) throws Exception {
    // Look at the following line: diamond operator and new.
    Set<Point> points = new TreeSet<>(new PointComparator());
}

static class PointComparator implements Comparator<Point> {

    @Override
    public int compare(Point p1, Point p2) {
        if (!p1.equals(p2)) {
            return -1;
        }
        return 0;
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top