I have an arraylist of objects, each containing a unique date in the following format
YEAR-DAY-MONTH HOUR:MINUTE:SECOND (example: 2010-02-10 23:32:14)
I’m trying to compare each object in the array list (there are a few thousand) with a incrementing timer class I created to check if both times match. It seems like the easiest way to check to see if the object and timer have matching dates would be to first sort the array list from earliest to latest, and then check each object individual, going on the next one in the list once one matches the timer. However, I’m not sure how I would sort an array list based on the previously mentioned time format. So far, my dated objects are have the following properties:
public float min;
public float hour;
public float day;
public float month;
public float year;
How could I sort an array list of these objects so that it was sorted from the earliest to latest date?
Potential simple solution
It seems to me that you’re reinventing the wheel here. There are plenty of types representing a date and time already – creating your own one is likely to lead to pain.
In this case I’d recommend using
LocalDateTimefrom Joda Time.Answering the actual question
You mention a “format” as if we’re really dealing with strings – but I can’t see anything about strings there.
Why are you using
floatvalues? These seem like natural integers – although you’ll want seconds as well.You could make your type implement
Comparable<T>fairly easily and naturally – then you just need to callCollections.sortand it will do the right thing. Here’s a sample implementation ofComparable<Foo>, assuming your type is calledFoo:chburd’s answer of implementing
Comparer<T>instead is equally valid; if your object is just a date/time, then you’ve got a natural sort order andComparable<T>is probably a better choice; if you actually have more properties in the object and you may want to sort by those instead, thenComparer<T>would be better.