Hi KC

Very nice observation, I confess always having some headaches myself with this kind of code.

The Comparator (java.util.Comparator) is an interface. One can define several comparators: one for String, another for Integer and so on. This means several small classes, one per comparator.

Instead of doing so, there is this dirty trick that allows to have everything in a sole class.

This is the dirty trick. Let's say you have a simple (a small number of methods) interface (or abstract class):

   // MyInterface.java
   public interface MyInterface {
       public String sayHello(String name);
   }

You can avoid writing the classes implementing this interface and use ad-hoc inline code, such as:

   // Test.java
   public class Test {
       public static void main(String[] args){
           *MyInterface my1 = new MyInterface(){ // The implementing
   class defined here**
                                             public String
   sayHello(String name){ return "Hello " + name; }
                                         };
           MyInterface my2 = new MyInterface(){ // Another implementing
   class defined here
                                             public String
   sayHello(String name){ return "Bonjour " + name; }
                                         };*
           String name = "Bond, James Bond";

           System.out.println( my1.sayHello(name));
           System.out.println( my2.sayHello(name));
       }
   }

With the dirty trick, it is possible to write only two java files (MyInterface.java and Test.java). Without it I had to write two more classes (with all the redundant heading code). It doesn't improve the code readability, but allows to write less code (which is important for a sample exercise).

In the case of the Comparator, the idea was to create a sole class file containing a "factory" and keeping together all the comparators.

Hope it helps
mihai

kc a écrit :
Hi,

I am confused on how the Comparator interface is used in Execise 5.2

    public static Comparator integerComparator() {
        return new Comparator() {

            public int compare(Object o1, Object o2) {
                int val1 = ((Integer)o1).intValue();
                int val2 = ((Integer)o2).intValue();
                return (val1<val2 ? -1 : (val1==val2 ? 0 : 1));
            }
        };
    }

instead of

public class MyComparator implements Comparator {

            public int compare(Object o1, Object o2) {
                int val1 = ((Integer)o1).intValue();
                int val2 = ((Integer)o2).intValue();
                return (val1<val2 ? -1 : (val1==val2 ? 0 : 1));
            }


}

Regards
KC


--
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/javaprogrammingwithpassion?hl=en

Reply via email to