Class Activity{
private int level;
private Activity predecessor;
}
My program creates instances of Activity, puts them in an Arraylist and sorts them by two fields level and predecessor. predecessor is first compared.
For instance, if predecessor is not null, the predecessor Activity of the current activity should be first and it will be second. After satisfying the predecessor condition the following could be ordered by level.
List<Activity> activities = new ArrayList<Activity>();
//Add some activities.
activities.add(Activity);
activities.add(Activity);
Collections.sort(activities,getActivityComparator());
private Comparator<Activity> getActivityComparator() {
return new Comparator<Activity>() {
public int compare(Activity act1, Activity act2) {
if (act1 == null) {
if (act2 == null) {
return 0; // Both activities are null
} else {
return -1; // act1 is NULL, so put act1 in the end of
// the sorted list
}
} else {
if (act2 == null) {
return 1;
}
}
Activity preAct2 = act2.getPredecessor();
if(preAct2!=null&&preAct2==act1)
return -1;
//Adding this by Joeri Hendrickx's suggestion
Activity preAct1 = act1.getPredecessor();
if(preAct1!=null&&preAct1==act2)
return 1;
return act2.getLevel()-act1.getLevel();
}
};
}
I have written the above code and tested a lot, but it outputted inconstant ordering if I putted different ordering into Arrarylist. so definitely this is incorrect method to implement this. Seems the root cause is not every two elements were compared. says Activity act1>Activity act2(by level condition), Activity act2>Activity act3(by level condition), it doesn’t mean Activity act1>Activity act3(by predecessor condition).
Here I came up with an new idea that is to use bubble sort instead of using interface sort of Collections. it will compare every two elements that don’t need comparator transitive any more. how do you think?
Can anyone help me?
The problem is that your comparator is not describing a correct symmetric and transitive relation.
Consider the following three objects:
Now, where comp is your comparator,
comp(act1, act2)will return -1, butcomp(act2, act1)will return 0. This is not symmetric.comp(act1, act2)will return -1,comp(act2, act4)will return -1, butcomp(act1, act4)will return 1. This is not transitive.A comparator must describe a correct reflexive, symmetric and transitive relation in order for it to work.
Edited after seeing Axtaxt’s post: the problem you describe here cannot be accomplished with a normal sort, because it’s always possible to construct a scenario where, by these rules, you get a loop in your sort hierarchy. So it’s not possible to make a transitive comparator with only this data.