-3

This is quite a simple problem, but I haven't been able to figure out what Java wants from me. Right now to demonstrate, I simply have the code:

Comparator<Integer> c;      

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

While also of course importing the comparator import java.util.Comparator;

NetBeans tells me "variable c may not have been initialized". What can I do to initialize c?

Cheers

Himanshu Agarwal
  • 4,623
  • 5
  • 35
  • 49
  • https://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/ – Tim Biegeleisen Dec 20 '17 at 04:30
  • 1
    You need to define the comparator in a meaningful way. – Tim Biegeleisen Dec 20 '17 at 04:30
  • You don't need a comparator if you use it only in the next line. Might just as well write `if (5 < 3)`. The idea is to decouple the code that defines the logic from the code that needs to use it. So you will want to pass it around into a method. – Thilo Dec 20 '17 at 04:31
  • General principle: make your variable reference an object before you go calling methods on it. Unlike languages like C and C++, declaring a variable does not create an object in Java. – Dawood ibn Kareem Dec 20 '17 at 04:32

1 Answers1

0

This is what you want (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");
    }
}

Using a comparator however, would make more sense in case of slightly more complex classes. For example, here is what you would do if you wanted a comparator to compare two points using their x-coordinate

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"); 
        }
    }
}
lakshayg
  • 2,053
  • 2
  • 20
  • 34