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

Implement a Comparator to compare objects

by Retired ‎02-16-2010 03:28 PM - edited ‎09-16-2010 02:59 PM (2,713 Views)



This article applies to the following:

  • BlackBerry® Java® Development Environment (BlackBerry JDE)
  • BlackBerry smartphones based on Java® technology



Comparators are used to impose total ordering on a set of objects. The ordering you can produce with comparison methods is the class's natural ordering, and the class's implementation of compare is its natural comparison method.


Usually comparators are passed to data structures that have sorting requirements but they can be used in any context when you want to compare two objects. Implementing your own custom comparators allows you to define the rules of how your objects fit into a total order, such as comparing class variables or comparing other application logic.


The following example shows how to implement the net.rim.device.api.util.Comparator interface to compare two objects. In this demonstration we compare Bag objects based on how many items they contain:



public class Bag {
private int iItemsInBag;

public Bag(int iItemsInBag) {
this.iItemsInBag = iItemsInBag;

public int getIItemsInBag() {
return iItemsInBag;

public void setIItemsInBag(int itemsInBag) {
this.iItemsInBag = itemsInBag;


import net.rim.device.api.util.Comparator;

public class BagComparator implements Comparator {

public int compare(Object o1, Object o2) {
Bag bag1 = (Bag)o1;
Bag bag2 = (Bag)o2;

//In order to compare bag objects we will compare the
//amount of items in the bags.

//A Negative integer if the first Bag is 'less than' the second.
//A positive integer if the first Bag is 'greater than'
//the second.
//A zero if the two Bags are 'equal'.

if (bag1.getIItemsInBag() < bag2.getIItemsInBag()) {
return -1;
} else if (bag1.getIItemsInBag() > bag2.getIItemsInBag()) {
return 1;
} else {
return 0;

public class Main {
public static void main(String[] args) {
BagComparator oBagComparator = new BagComparator();
Bag bag1 = new Bag(20);
Bag bag2 = new Bag(25);

int iCompareResult = oBagComparator.compare(bag1, bag2);

if (iCompareResult < 0) {
System.out.println("Bag1 is less then bag2.");
} else if (iCompareResult > 0) {
System.out.println("Bag1 is greater then bag2 ");
} else {
System.out.println("The two bags are equal.");




Users Online
Currently online: 22 members 909 guests
Please welcome our newest community members: