1

I'm trying to sort an array of objects according to the DateTime of the objects. I've used the following example to create my solution:

Sort objects in ArrayList by date?

The method I use looks like this:

        List<SomeEvent> myEvents = new ArrayList<>();
//...
//left out the part where the List is filled with Objects
//...
        Collections.sort(myEvents, new Comparator<SomeEvent>() {
            public int compare(SomeEvent se1, SomeEvent se2) {
                return se1.getStartTime().compareTo(se2.getStartTime());
            }
        });

I get the error message "Cannot resolve method 'compareTo(com.google.api.client.util.DateTime)'

Any pointers as to what I'm missing?

Edit: My class SomeEvent now implements Comparable as suggested:

public class SomeEvent extends SomeTask implements Comparable<SomeEvent>
{ 
private DateTime startTime; 

private DateTime endTime;


     public DateTime getStartTime() {
         return startTime;
     }

     public DateTime getEndTime() {
         return endTime;
     }

 }

Now, however, I get the hint that I need to either declare my class as abstract (which is not possible in the context it is used) or implement the abstract method 'compareTo(T)' in 'Comparable'.

How can I implement the abstract method?

Community
  • 1
  • 1
Sorcha
  • 21
  • 3
  • 1
    Your `SomeEvent` class doesn't implmenet comparable interface – Pragnani Feb 25 '16 at 14:41
  • @PragnaniKinnera: Ok, thanks for the hint, but if I implement the comparable interface like this: public class SomeEvent extends SomeTask implements Comparable { ... } I am told that I must either declare the class as abstract (which is not an option) or implement the abstract method 'compareTo(t)' in 'Comparable'. How do I do this? – Sorcha Feb 25 '16 at 15:07
  • @PragnaniKinnera *"Your `SomeEvent` class doesn't implmenet comparable interface"* ... it doesn't need to. – Tom Feb 25 '16 at 15:29

1 Answers1

1

Could you try this

Collections.sort(myEvents, new Comparator<SomeEvent>() {
        public int compare(SomeEvent se1, SomeEvent se2) {
            return (int) (se1.getStartTime().getValue() - se2.getStartTime().getValue());
        }
    });

So, I see, you are using not java.util.Date, where compareTo method exists, but com.google.api.client.util.DateTime, in which there is no compareTo method.

Solorad
  • 904
  • 9
  • 21
  • That is definitely my problem, thank you. However, now I have to work out some syntax error, it doesn't work like this quite yet. – Sorcha Feb 25 '16 at 15:49
  • @Sorcha, I updated answer, could you please check it? – Solorad Feb 25 '16 at 15:57
  • The current problem is strange - it tells me "unnecessary semicolon" in the third line (the one after getValue()), but tells me that a semicolon is expecte ("; expected") and "unexpected token" at the same time. So right now I've fixed it by casting the DateTime to Date and using the original function. – Sorcha Feb 25 '16 at 15:57