Reputation: 7190
I have an arraylist of several items. An item may have a specific int field LYING equal to OFF, FLOOR, RB1, RB2, RB3 or RB4.
For example OFF is defined as:
public static final int OFF = 0;
Regarding some specific global variables I would like to order those elements in a custom way, that may be for example:
Which is the best solution for my case?
Focusing on writing some custom:
public int compare(Object o1, Object o2) {
if(globalVariable0 > 0) {
if(o1.getLying() == o2.getLying)
return 0;
if(o1.getLying() == RB1 && o2.getLying != RB1)
return -1;
...
}else{
...
}
or..?
Upvotes: 1
Views: 132
Reputation: 12780
From your question I understand that you wnat to group elements by their LYING.
I would then keep several lists, one for each LYING... You could also an Enum for the different LYINGs.
You could store your elements in a Multimap, or use, for example:
static enum Lying {
OFF, FLOOR, RB1, RB2, RB3, RB4
}
EnumMap<Lying , List<MyElements>> myElements = ...
Upvotes: 0
Reputation: 5438
There are probably several solutions for this but since we are talking about an "unnatural" order I'd hold an object with the correct order, for example a map that I can query for sortposition in my compare method, then the sortorder could be easy to edit in a properties-file maybe. Perhaps like this:
public int compare(Object o1, Object o1){
ActualType a1 = (ActualType) o1;
ActualType a2 = (ActualType) o2;
SortedOrderMap map = getSortOrderMap(); //cached of course
Integer l1 = map.get(a1.getLying());
Integer l2 = map.get(a2.getLying());
return l1.compareTo(l2);
}
Upvotes: 2