简体   繁体   中英

object sorting using comparable interface

i have one class which have 4 int fields . i want to sort objects array by some mathematical operation on fields .I tried below code but sorting is not happening.

class Cust1 implements Comparable<Cust1>{

    int a;
    int o;
    int s;
    int p;
    @Override
    public int compareTo(Cust1 b) {
        if(this.a + this.s <= b.a + b.s)
        {
            return 1;
        }
        else {
            return 0;
        }
    }   
}

public class Test5 {

    public static void main (String args[]) throws Exception
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        Cust1[] cust = new Cust1[n];
        for(int i=0;i<n ;i++)
        {
            Cust1 a = new Cust1();
            String[] str = br.readLine().split(" "); 
            a.a = Integer.parseInt(str[0]);
            a.o = Integer.parseInt(str[1]);
            a.s = Integer.parseInt(str[2]);
            a.p = Integer.parseInt(str[3]);
            cust[i] =a;
        }
        Arrays.sort(cust, new Comparator<Cust1>() {
                @Override
                public int compare(Cust1 o1, Cust1 o2) {
                    return o1.compareTo(o2);
                }
        });
    }
}

Based on your code snippet: you don't need to provide Comparator , since Cust1 already implements Comparable . So, this should be enough:

Arrays.sort(cust);

Also, Cust1 implementation of Comparable doesn't really tell, when one object is less then other. Probably, you meant something like this:

    @Override
    public int compareTo(Cust1 b) {
        if(this.a + this.s < b.a + b.s) {
            return 1;
        } else if (this.a + this.s > b.a + b.s) {
            return -1; 
        } else {
            return 0;
        }
    } 

But it's hard to tell, what exact implementation of Comparable should be without more details (for instance, for some reason fields o and p are not involved in comparison at all).

You comparator work wrong. It should return:

  • >0 - current object is greater than another one
  • 0 - current object is equal to another one
  • <0 - current object is less than another one

    class Cust1 implements Comparable {

     int a; int o; int s; int p; @Override public int compareTo(Cust1 b) { return Integer.compare(a + s, ba + bs); }

    }

And you do not have to provide additional comparator to Arrays.sort() since Cust1 already implements Comparable .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM