views:

462

answers:

3

hi,

i have an arraylist of objects, each containing a year/month/day/hour property. what i'm ultimately trying to do, is create a new multidimensional array that contains a group of every object by incrementing hour. so for instance, an example of the final array i'd want is:

array: [0]
            [0] 01:04:00, 4-10-09
            [1] 01:15:00, 4-10-09
       [1]
            [0] 02:25:00, 4-10-09
       [2]
            [0] 06:14:00, 4-10-09
            [1] 06:27:00, 4-10-09
       [3]   
            [0] 04:03:00, 4-11-09
            [1] 04:11:00, 4-11-09

i'm having a difficult time figuring out to properly sort arraylists in java though. how could i sort each section (year,month,day,hour) within the arraylist in ascending order, before inserting them into an final array?

thanks.

+2  A: 

Check out Comparators http://java.sun.com/j2se/1.4.2/docs/api/java/util/Comparator.html

Comparator is an interface with the method compare(Object1, Object2) in which you can compare the dates You then define your own comparator object which implement comparator and then use Collections.sort(Arraylist, comparator)

Aly
+2  A: 

To sort a collection you can make a call like this:

List<MyDate> dates = ... 
Collections.sort(dates);

The MyDate class will need to implement the interface Comparable which will require the method "int compareTo(object o)" to be implemented.

In the "compareTo" method, you can then write the code which will call the getters for the year, month, and so on until it figures out whether the current object is less than, equal to or greater than the object "o" being passed into the compareTo method.

Example:

public int compareTo(Object o) {
    MyDate otherDate = (MyDate) o;
    int thisYear = this.getYear();
    int otherYear = otherDate.getYear();
    if (thisYear < otherYear) return -1;
    if (thisYear > otherYear) return 1;
    // Now try the month, then day etc
}
digiarnie
worked like a charm. thanks!
minimalpop
A: 

Implement the comparable interface on your time/date object. Then it would be as easy as doing Collections.sort

Sands