1

I'm trying to create an Comparator on my custom type.

Type {
    int state = 0; // can be 0 or 1
    String name = ""; // can be anything
}

I'm trying to sort the list so, that at first, on the top of list are items with one state and on the bottom the other state.

And in second step, items in both section (section 1: state 0, section 2: state 1), are sorted alphabetically.

I've tried this:

    @Override
    public int compare(Type i1, Type i2) {
        boolean a = i1.state == 1;
        boolean b = i2.state == 1;
        if (a && b) {
            return i1.name.compareTo(i2.name);
        } else if (a && !b) {
            return 1;
        } else {
            return -1;
        }
    }

But item's get kind of randomized with each item state change.

List with these items:

name : A B C D E F G H I J K
state: 1 0 1 1 0 1 0 0 1 1 0

should be listed like this:

B 0
E 0
G 0
H 0
K 0
A 1
C 1
D 1
F 1
I 1
J 1

Have anybody an idea how to solve it? Thanks

1
  • please say what is the Type token there in the first step? Commented Feb 16, 2012 at 12:18

2 Answers 2

3

Your code breaks when both states are equal to zero. You could fix it by using this condition

if (a == b) ...

instead of

if (a && b)

...or try this instead:

@Override
public int compare(Type i1, Type i2) {
    int res = i1.state - i2.state;
    if (res == 0) {
        return i1.name.compareTo(i2.name);
    } else {
        return res;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

oh god, I'm so unable to think today. Thanks. It's clear as day, when I think about it like this now...
I'd also suggest to have an enum for state instead of using just integers
0

Why don't you implement Comparable and put the same logic in the compareTo method?

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.