0

I have the following class:

    int x;
    int y;
    float distance;

    public Point(int x, int y, float distance){
        this.x = x;
        this.y = y;
        this.distance = distance;
    }
}

On my main program I have this line:

PriorityQueue<Point> minHeap = new PriorityQueue<Point>( (a,b) -> ((float) a.distance - (float) b.distance) );

I keep getting this error:

        PriorityQueue<Point> minHeap = new PriorityQueue<Point>( (a,b) -> ((float) a.distance - (float) b.distance) );
                                                                                              ^
    possible lossy conversion from float to int```
------------------------------------------------------------------------------------

I dont know why is not accepting my comparator method. Any ideas? thanks in advance.
ChristianS
  • 51
  • 2

1 Answers1

4

That's because the compare method you're defining returns an int, but since you're getting an int with an operation between floats the compiler tells you some data might get lost (it actually will, all the decimals, but you don't really care since it's just a comparator).

You could use Float.compare(f1, f2) in

PriorityQueue<Point> minHeap = new PriorityQueue<Point>( (a,b) -> Float.compare(a.distance, b.distance));
Balastrong
  • 4,336
  • 2
  • 12
  • 31
  • 1
    Thinking again about it, you *do* care about the decimals. If you compare `10.1` with `10.9` and return an `int`, you'll get `0` and the comparator will treat the numbers as equal, but they're not. You're welcome ^^ – Balastrong May 30 '20 at 15:39