tbboyett
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
Thanks for your help
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
:-)
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
//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("sorted
}
public static class CompareStatusesCustom implements Comparator {
public int compare(Object o1, Object o2)
{
return String.CASE_INSENSITIVE_OR
}
}
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_OR
}
}
}