-2

I have this code:

Flight.java

public static Flight[] sortFlight(Flight []f)
{
    for(int i =f.length;i>=0;--i)
    {
        for(int j=0;j<=i;j++) 
        {
            int myFlightNum1 = f[i].getFlight_number();
            int myFlightNum2 = f[j].getFlight_number();

        if(myFlightNum1>myFlightNum2)
            {
            int temp = f[i].getFlight_number();
            f[i].setFlight_number(myFlightNum2);
            f[j].setFlight_number(temp);

            }
        }
    }
return (f);

I want to sort the array based on flight number. I have tried Arrays.sort, but it keeps on saying cannot be cast to java.lang.comparable.

FlightTest.java

public static void main(String[] args) {
    Flight[] f = {

            new Flight("US Air","Boston","Los Angeles", 347),
            new Flight("Delta","Pheladelphia","London",212),
            new Flight("Continental","Atlanta","Chicago",822)
            };

    System.out.println("This flight information is sorted based on flight number:");

    for (Flight flights : f)
        {

        System.out.println(flights);
        }

}
Andronicus
  • 25,419
  • 17
  • 47
  • 88

3 Answers3

4

You can provide Comparator in sort method as second parameter:

Arrays.sort(f, Comparator.comparing(Flight::getFlight_number));

Comparable interface is not a must really.

Andronicus
  • 25,419
  • 17
  • 47
  • 88
2

One solution is to have your Flight class implement the comparable interface. This would guarantee that it has to implement the compareTo() method, where you will have to define how to compare one Flight object with another.

Bill
  • 1,407
  • 10
  • 18
0

If your Flight object implements Comparable and there you can set your own logic for comparing the fields you need then you could just use Arrays.sort() function. See here for an example: https://www.tutorialspoint.com/java/util/arrays_sort_super.htm

hasan
  • 553
  • 1
  • 5
  • 19