Sorting a time intervals

后端 未结 5 872
逝去的感伤
逝去的感伤 2021-01-27 12:25

I am giving a time interval in the form of two arrays.

A[0]=  2  B[0]=3
A[1]=  9  B[1]=11
A[2] = 5 B[2]=6
A[3] = 3 B[3]=10

I want to sort the i

5条回答
  •  广开言路
    2021-01-27 12:54

    instead having two arrays, create object which holds your intervals

    class Interval  implements Comparable  {
    
    private Long start,completed
    
     public Interval(Long start, Long completed) {
            this.start = start;
            this.completed = completed;
    }
    
    
      @Override
      public int compareTo(Interval o) {
        return start.compareTo(o.start);
      }
    
    //getters and setters ommited
    }
    

    then, all what you need to do is implement compareTo method and put all your data in some collection ie List intervals

    and used Collections.sort(intervals) to sort them

    EDIT

    Example:

    originally you have:

    A[0]=  2  B[0]=3,
    A[1]=  9  B[1]=11
    A[2] = 5 B[2]=6
    A[3] = 3 B[3]=10`
    

    lets replace this by:

    List intervals = new ArrayList<>();
    intervals.add(new Interval(2L,3L));
    intervals.add(new Interval(9L,11L));
    intervals.add(new Interval(5L,6L));
    intervals.add(new Interval(3L,10L));
    //NOTE L is added at the end variable as interval uses Long, if you change it to integer you dont need to add it;
    

    And now all what you need to do is sort

    Collection.sort(intervals);
    

提交回复
热议问题