0

I want to sort a List of Objects (Remarks) by a value contained in another object (DefectClass).

public class Remark {
private int remarkId;
private DefectClass defectClass;
}

I have a List of Remarks and I'm using this code to sort them by the title of the defectClass :

Collections.sort(remarks, new Comparator<Remark>()
            {
                @Override
                public int compare(Remark arg0, Remark arg1) {
                return arg0.getDefectClass().compareTo(arg1.getDefectClass());
                }
            });

and this is the Compare to methode in my DefectClass model :

public class DefectClass implements Comparable<DefectClass> {
private String DefectClassTitle;
/* Getters And Setters */
    @Override
public int compareTo(DefectClass o) {
    if(o.getDefectClassTitle().equals(this.getDefectClassTitle()))
        return 0;
    else
        return 1;
}

by these codes I want to sort a List of remarks by the Title of the DefectClass of these Remarks ... but At the end I always get the same list with no sorting. What I'm doing wrong ?

5
  • use either one. 1). Collections.sort() with new Comparator 2.) Collections.sort() for the class that implements Comparable. Commented Jun 1, 2014 at 18:58
  • use return o.getDefectClassTitle().compareTo(this.getDefectClassTitle()). You're never returning -1 otherwise. Commented Jun 1, 2014 at 18:58
  • 1
    Check compareTo contract, you must return -1, 0 and 1. Commented Jun 1, 2014 at 18:59
  • You must create an order with your compareTo method. You must not check for equality but determine which one is greater or lower. Commented Jun 1, 2014 at 19:00
  • 1
    Use first option if you want to sort on different properties of the class. Commented Jun 1, 2014 at 19:01

2 Answers 2

4

The implementation of the DefectClass.compareTo() method is incorrect, as it should compare the 2 objects and return whether the first one is lower (-1), equal(0) or greater (1) to the second one (and not only indicate whether they're equal as in your case). Assuming getDefectClassTitle() is returning String I'd implement the method as:

public int compareTo(DefectClass o) {
    return o.getDefectClassTitle().compareTo(this.getDefectClassTitle());
}  
Sign up to request clarification or add additional context in comments.

Comments

1

You need not even implement Comparable, as you are providing your own Comparator.
Use it as follows:

Collections.sort(remarks, (r1, r2) -> r1.getDefectClass().getDefectClassTitle().compareTo(r2.getDefectClass().getDefectClassTitle()));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.