1

I want to sort a wrapper class list which has a reference to another wrapper in it.I tried implementing Comparable interface for both of class but it is showing error

One or more of the items in this list is not Comparable.

Please suggest me some way to do this.

i want to sort list by name and number.i will use a field sortBy for this purpose.

Class A{

list<WrapperB> listOfB{get;set;}
public A(){
   listOfB.sort();
}
class WrapperB {
String name{get;set;}
public WrapperC ref{get;set;}
}

class WrapperC{
String number;
} 
}

1 Answer 1

3

I would write this code:

Class A {

    list<WrapperB> listOfB {get;set;}

    class WrapperB implements Comparable {

        String name {get;set;}
        public WrapperC ref {get;set;}

        public Integer compareTo(Object o) {
            WrapperB that = (WrapperB) o;
            if (this.name < that.name) return -1;
            else if (this.name > that.name) return 1;
            else return this.ref.compareTo(that.ref);
        }
    }

    class WrapperC implements Comparable {

        String number;

        public Integer compareTo(Object o) {
            WrapperC that = (WrapperC) o;
            if (this.number < that.number) return -1;
            else if (this.number > that.number) return 1;
            else return 0;
        }
    } 
}

When WrapperB.name values are the same, WrapperC.number defines the sort order. This code assumes no null values are present.

The original code posted would always NPE because listOfB would be null when the constructor ran.

1
  • 1
    Yes, it is essential to implement Comparable interface if you are trying to sort a wrapper class. May 23, 2015 at 10:31

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .