Java bods in here please

Associate
Joined
19 Sep 2005
Posts
1,242
Any Java bods in the house? If so, could I add you to MSN for a quick chat? Need a little assistance with a Comparator class I'm writing.

Danke :)
 
Been asked to write a Comparator class. Then Implement a new Constructor for another class that passes a Comparator. Haven't a clue where to start. :(
 
Post up! Share the love! :)

As for the constructor bit:
Code:
public class Foo
{
  private Comparator comparator;

  public Foo (Comparator comp)
  {
    this.comparator = comp;
  }
}
:)
 
Code:
//This is the Comparator
public class Comparison implements Comparator
{
   //This method takes two objects, compares them and returns the result
    public int compare(Object o1, Object o2)
    {
        //Program logic
       return -1;
    }
}

//This object makes use of comparators to compare two strings
public class OtherClass
{
    public OtherClass(Comparator c)
    {
        //Compare two strings using the given comparator. Different comparators may give different results.
        if(c.compare(new String("test"), new String("test 2"))
             //do something
    }
}


//Sample main method making use of the above
public static void main(String[] args)
{
    Comparator c = new Comparison();
    OtherClass obj = new OtherClass(c);
}

Is that the sort of thing you're after?
 
Last edited:
Create an instance of it and pass it as you would any other variable, as in my example.

You can use Interfaces as types as you would any other, so if you'd normally pass a String like this:

Code:
public void printLowerCase(String s)
{
     System.out.println(s.toLowerCase());
}

Notice that String is an object so you can run methods on it after passing an instance of it to the method. Now apply that idea to Comparators:

Code:
public void printComparison(String s0, String s1, Comparator c)
{
     if(c.compare(s0,s1))
          System.out.println("They're the same!");
     else
          System.out.println("They're not the same!");
}

In this case you're just passing an instance of a Comparator to the method and can then use it as if you'd created it in the method. To call this method you could do something like this:

Code:
printComparison("foo", "bar", new Comparison())

The same theory applies for passing Comparators to constructors of Objects, though in that case you'd probably want to store the reference in a variable.
 
Back
Top Bottom