1

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:

  • all the RB1 items at the begin of the arraylist, all the RB2 items after any RB3 items (regardless the OFF items) and all the RB4 at the end of the arraylist.

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..?

1
  • Are OFF, FLOOR, RB1/2/3/4 enums? In that case, cant you just: public int compareTo(Object other) { return this.getLying().value() - other.getLying().value(); } Commented Jan 22, 2013 at 9:48

2 Answers 2

2

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Interesting, and what about if I would need to order based on more than one factor, that is not only the lying but also other parameter(s)?
@elect That depends on the cardinality of your data. In your example it seems like there are not a lot of sortpositions, then you would benefit to build a lookup-table. If there are infinite (or at least unpractical number) of sortpositions you need to handle that in another way, perhaps two lookup-tables? :-)
0

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 = ...

1 Comment

I want to group, but I also want to keep them within the main Arraylist

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.