Ali
Ali

Reputation: 11590

how to sort the Vector containing objects using Blackberry API

I want to sort a vector which contains Object of following fields

public class CategoryListing   {

     String company_id;
     String company_name;
     double distance;

     //setters and getters here 
}

I populated the vector from webservice, now I want to sort that vector by distance, means I want to show nearest one. How can I sort the vector which contains objects?

Upvotes: 1

Views: 771

Answers (2)

rfsk2010
rfsk2010

Reputation: 8611

None of the other answers are going to work for you on Blackberry as it doesn't support Generics. Blackberry uses older version of Java. Try the following code. It uses SimpleSortingVector

    SimpleSortingVector sortVector = new SimpleSortingVector();
    sortVector.setSortComparator(new Comparator() {

        public int compare(Object o1, Object o2) {

            CategoryListing o1C = (CategoryListing)o1;
            CategoryListing o2C = (CategoryListing)o2;
            return Double.toString((o1C.distance)).compareTo(Double.toString(o2C.distance));
        }
    });
            //when you add elements to this vector, it is automatically sorted by distance
    sortVector.addElement(new CategoryListing());

Upvotes: 4

Amit Deshpande
Amit Deshpande

Reputation: 19185

You can use Comparator.

Define a comparator which will sort on distance like below

public class DistanceComparator implements Comparator {
    public int compare(Object o1, Object o2) {
        return Double.valueOf(((CategoryListing) o1).distance)
                .compareTo(((CategoryListing) o2).distance);// use getters
    }
}

Sort vector using below sort method. Note As Arrays are present from 1.2 It is also present for blackberry.

public static void sort(Vector vector,Comparator comparator) {

    Object[] array = new Object[vector.size()];   
    vector.copyInto(array);   

    Arrays.sort(array,comparator);

    int i = 0;
    Enumeration enumumeration = vector.elements();
    while (enumumeration.hasMoreElements()) {
        enumumeration.nextElement();
        vector.insertElementAt(array[i++], i);
    }
}

Upvotes: 2

Related Questions