Comparator interface java

There are two ways to compare objects of a list .First one is to use compareTo method and for that we have to implement Comparable interface if we are comapring user defined classes.

Another way is to use Comparator interface. For that we don't have to implement Comparable interface on the class we are comparing.We can just use its single method "compare" to compare items

  static final Comparator<Seat> PRICE_ORDER  = new Comparator<Seat>() { }

Above we are not making an object of Comparator but instead we are creating an anonymous inner class that define the single method compare of Comparator.

In the example below we are using compare mehtod of Comparator to compare two seat objects.We are passing two objects seat1 and seat2 to compare method and then just checking the price and deciding based on price if two seat objects are equal . So two seats can have same price but that doesn't mean seat objects are equal as thet might have other variable that are different.So we have to do further testing here based on other variable likes seatNumber etc.

But the example on Comparator we compare seat class object just on the basis of price is below and it returns 0 if prices of two ojects are equal

   static final Comparator<Seat> PRICE_ORDER  = new Comparator<Seat>() {
        @Override
        public int compare(Seat seat1, Seat seat2) {
            if(seat1.getPrice()<seat2.getPrice()){ {return -1;}
            }
            else if(seat1.getPrice()>seat2.getPrice()){
                return 1;
            }
            else {
                return 0;
            }
        }
    };