Link to home
Start Free TrialLog in
Avatar of tbboyett
tbboyettFlag for United States of America

asked on

Sorting a vector using comparator

I have a vector of objects.  Each object contains status, from, and to.  I'm guessing I'd need to use comparator but uncertain as to how to implement it so that it will sort on any of the three criteria.

Thanks for your help
Avatar of borislavmarkov
borislavmarkov

You can sort by two ways: you provide Comparator, or your objects are implementing Comparable.
In firt variant you can sort objects from any type as long as Comparator you provide is accurate(I used string sort of string representation). In second variant you can only sort objects that "knows about each other". That's why I removed strings and numbers. I think example is self talking. For more info read javadoc of Collections.sort().


import java.util.Vector;
import java.util.Comparator;
import java.util.Collections;

public class Dummy
{
    public static void main(String[] args)
    {

        //WAY 1, with Comparator
        Vector v = new Vector();
        v.add("completed");
        v.add("started");
        v.add(new Integer(1));
        v.add(new Object(){ public String toString(){return "unknown";}});
        Collections.sort(v,new CompareStatusesCustom());
        System.out.println("sorted:" + v);

        //Way 2, each object must implement comparable,
        //Strings and numbers objects have compareTo method
        // so we only have to make our custom object to be comparable
        Vector v2 = new Vector();
        v2.add(new MyObject("completed"));
        v2.add(new MyObject("started"));
        v2.add(new MyObject("unknown"));
        Collections.sort(v2);
        System.out.println("sorted2:" + v2);

    }
    public static class CompareStatusesCustom implements Comparator {
        public int compare(Object o1, Object o2)
        {
            return String.CASE_INSENSITIVE_ORDER.compare(String.valueOf(o1),String.valueOf(o2));
        }
    }

    public static class MyObject extends Object implements Comparable
    {
        private String value;

        public MyObject(String value)
        {
            this.value = value;
        }

        public String toString(){return value;}

        public int compareTo(Object o)
        {
            return String.CASE_INSENSITIVE_ORDER.compare(toString(),String.valueOf(o));
        }
    }
}
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
:-)