Welcome!

Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

Java Development

Reply
New Contributor
nishnatgshah
Posts: 2
Registered: ‎05-15-2013
My Device: 9650
Accepted Solution

How to sort Dates from ArraList of model

I read about sorting ArrayLists using a Comparator but in all of the examples people used compareTowhich according to some research is a method for Strings.

I wanted to sort an ArrayList of custom objects by one of their properties: a Date object (getStartDay()). Normally I compare them byitem1.getStartDate().before(item2.getStartDate()) so I was wondering whether I could write something like:

 

 

public class customComparator {
    public boolean compare(Object object1, Object object2) {
        return object1.getStartDate().before(object2.getStartDate());
    }
}

public class randomName {
    
    Collections.sort(Database.arrayList, new customComparator);
    
}

 

 

Contributor
himen
Posts: 18
Registered: ‎05-15-2013
My Device: 9700

Re: How to sort Dates from ArraList of model

Classes that has a natural sort order (a class Number, as an example) should implement the Comparable interface, whilst classes that has no natural sort order (a class Chair, as an example) should be provided with a Comparator (or an anonymous Comparator class).

Two examples:

 

public class Number implements Comparable<Number> {
    private int value;

    public Number(int value) { this.value = value; }
    public int compareTo(Number anotherInstance) {
        return this.value - anotherInstance.value;
    }
}

public class Chair {
    private int weight;
    private int height;

    public Chair(int weight, int height) {
        this.weight = weight;
        this.height = height;
    }
    /* Omitting getters and setters */
}
class ChairWeightComparator implements Comparator<Chair> {
    public int compare(Chair chair1, Chair chair2) {
        return chair1.getWeight() - chair2.getWeight();
    }
}
class ChairHeightComparator implements Comparator<Chair> {
    public int compare(Chair chair1, Chair chair2) {
        return chair1.getHeight() - chair2.getHeight();
    }
}

New Contributor
nishnatgshah
Posts: 2
Registered: ‎05-15-2013
My Device: 9650

Re: How to sort Dates from ArraList of model

Thanks for quick reply