0

how can I sort Event by index?

simple view of my project:

class Event{
    int index; 
}

class EventField{
    Event[] field;
}

class Action{
    EventField ev;
    ev.sort();    // Sort event in field EventField by index
}

4 Answers4

0

You need to implement method in EventField

class EventField{
    Event[] field;

    public void sort(){ Arrays.sort(field, yourCustomComparatorInstance }
}

that does sorting using a custom Comparator on Event

Related:

See

Community
  • 1
  • 1
jmj
  • 237,923
  • 42
  • 401
  • 438
  • 1
    As your related question, don't use `return o1.getX() - o2.getX();`, as it could overflow when you compare a number close to `Integer.MIN_VALUE` with a one close to `Integer.MAX_VALUE`. See [this](https://ideone.com/ykTwQr). – Alexis C. Feb 26 '14 at 19:58
0

Use Arrays.sort() with Comparator<Event> which is using Integer.compare()

Arrays.sort(ev.field, new Comparator<Event>(){
    @Override
    public int compare(Event e1, Event e2) {
        return Integer.compare(e1.index, e2.index)
    }
});
n1k1ch
  • 2,594
  • 3
  • 31
  • 35
0

In java you have 2 ways to define order you can create a Comparator for creating your sort strategy, or define natural-order of your class implementing Comparable

Example using Comparator:

class Event{

private int index;
public static final Comparator<Event> INDEX_COMPARATOR = new MyComparator();

//TODO define getters and setter equals & hashCode cause it's strong recommended

static class MyComparator implements Comparator<MyClass>{

            @Override
            public int compare(Event o1, Event o2) {
                return Integer.valueOf(o1.index).compareTo(o2.index);
            }    
}

}

And then in EventField.

Example:

class EventField{
    Event[] fields;

   public void sort(){
     Arrays.sort(fields,Event.INDEX_COMPARATOR );
   }

 }

Read more : Collections#sort(..)

If you want to define natural-ordering of your class just define

public class Event implements Comparable<Event>{
        private int index;

        //define getter&setter & recommended equals & hashCode    

        @Override
        public int compareTo(Event o) {
           return Integer.valueOf(index).compareTo(o.index);
        }
}

And in EventField code:

   Arrays.sort(fields); // where fields is Event[]
nachokk
  • 14,363
  • 4
  • 24
  • 53
0

If events are naturally something you'll be comparing a lot in your program, you can extend the Comparable interface:

public class Event implements Comparable<Event> {
    private int index;

    public int getIndex() {
        return index;
    }

    @Override
    public int compareTo(Event o) {
        return index == o.getIndex() ? 0 : (index > o.getIndex() ? 1 : -1);
    } 
}

Then you can call Arrays.sort(ev.getField()). If the objects in 'field' are always going to be sorted, then you can just keep its objects sorted whenever you add something to it.

benjammin
  • 537
  • 5
  • 23