DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 2 of 2
  1. #1
    Join Date
    Dec 2004

    Lightbulb who can explain this code?????????

    can you Explain the workings of this code Specifically, the lines in bold font
    can you?

    import java.util.*;
    public class WhichComparator implements Comparator {
    protected Comparator base;

    public WhichComparator(Comparator baseCompare) {
    base = baseCompare;
    public int compare(Object obj1, Object obj2) {
    return -base.compare(obj1, obj2);

    public static void main(String[] args) {
    Vector arr = new Vector();
    Random ran = new Random();

    for(int i = 0; i < 10; i++)
    arr.add(new Integer(ran.nextInt(100)));
    System.out.println("Array before sorting!!!");

    Comparator c = new RevComparator(new IntegerComparator());

    Collections.sort(arr, c);

    System.out.println("Array after sorting!!!");
    } // End of class WhichComparator

    class IntegerComparator implements Comparator {
    public int compare(Object o1, Object o2) {
    Integer i1 = (Integer) o1;
    Integer i2 = (Integer) o2;
    if(i1.intValue() == i2.intValue())
    return 0;
    else if(i1.intValue() > i2.intValue())
    return 1;
    return -1;
    } // End of class IntegerComparator

  2. #2
    Join Date
    May 2004
    Durham, UK

    Here goes,

    the Collections.sort method as it does not know what items you are attempting to sort it requires a Comparator class to help.

    A Comparator class has a two methods, compare and equals - I believe that sort only uses the compare method.

    The compare method is used to compare the two arguments.

    If they are equal - return 0
    if the first is greater than the second - return 1
    if the second is greater than the first - return -1

    The line

    public int compare(Object obj1, Object obj2) {
    return -base.compare(obj1, obj2);
    Looks to be taking the return from the base.compare method, and negativising it, thus creating a reverse sort.

    The other two lines highlighted
    Comparator c = new RevComparator(new IntegerComparator());

    Collections.sort(arr, c);
    are just creating a Comparator object , and using the static sort method of Collections to perform the sort.

    Hope this helps

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center
Latest Articles
Questions? Contact us.
Web Development
Latest Tips
Open Source

   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center

We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.