如何初始化比较器?它表示变量可能尚未初始化

时间:2017-12-20 04:28:45

标签: java initialization comparator

这是一个非常简单的问题,但我还没有弄清楚Java想要什么。现在要演示,我只需要代码:

Comparator<Integer> c;      

if (c.compare(5, 3) < 0) {
    System.out.println("yep, it's less");
}

当然还要导入比较器import java.util.Comparator;

NetBeans告诉我&#34; 变量c可能尚未初始化&#34;。我该怎么做才能初始化c

干杯

1 个答案:

答案 0 :(得分:0)

这就是你想要的(Java 8)

import java.util.Comparator;

public class ComparatorDemo {
    public static void main(String... args) {

        // (1) Defining a custom comparator using lambda
        // Comparator<Integer> c = (Integer a, Integer b) -> a - b;

        // (2) comparingInt takes a lambda which maps from object you want to compare to an int
        Comparator<Integer> c = Comparator.comparingInt(a -> a);

        if (c.compare(3, 5) < 0)
            System.out.println("Yes, It's less");
    }
}

然而,使用比较器,在稍微复杂的类的情况下会更有意义。例如,如果您希望比较器使用其x坐标

比较两个点,您可以执行此操作
import java.util.Comparator;

class Point {
    private int x;
    private int y;

    public Point(int x, int y) { this.x = x; this.y = y; }
    public int getY() { return y; }
    public void setY(int y) { this.y = y; }
    public int getX() { return x; }
    public void setX(int x) { this.x = x; }
}

public class ComparatorDemo {
    public static void main(String... args) {
        Comparator<Point> pc = Comparator.comparing(Point::getX);
        Point p1 = new Point(1, 2);
        Point p2 = new Point(2, 2);
        if (pc.compare(p1, p2) < 0) {
           System.out.println("Yes, it's less"); 
        }
    }
}