-
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!!!");
System.out.println(arr);
Comparator c = new RevComparator(new IntegerComparator());
Collections.sort(arr, c);
System.out.println("Array after sorting!!!");
System.out.println(arr);
}
} // 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;
else
return -1;
}
} // End of class IntegerComparator
-
Hi,
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
Graham
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
Forum Rules
|
Top DevX Stories
Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL
|
Bookmarks