1

Say I have a function foo, with some parameters. In this function I generate an array m of type Move. I now need to sort this array. Ok, so I break out Arrays.sort(m, Comparator() { ... }. But wait, the function I want to use to compare two moves needs to take the parameters of foo into account, yet a Comparator's compare function can only take two arguments of type Move! See following code for what I want to do.

public int compare (Move m1, Move m2, Game g, int id) {
    return g.evaluate(m1, g, id) - g.evaluate(m2, g, id);
}


public int foo (Game g, int id) {
    Move[] m = ... ;

    ???

    // m is now sorted by compare(move1, move2, g, id)
}

I do not have access to the Game class itself, so I can't just edit that to solve my problem. The Comparator class seems unable to do this. Is there any way to actually do this in Java?

4
  • You can create a wrapper around game and then sort that using a comparator . Commented Oct 29, 2014 at 20:04
  • 2
    Make a MoveComparator class that is constructing using a Game and an int, and stores them as instance variables. The MoveComparator can then compare the two Moves it's passed using the Game and int it already has. Commented Oct 29, 2014 at 20:04
  • You could subclass comparator and provide your parameters to it rather that use an anonymous comparator. Then in your implementation which is doing the comparisons you could use those values. Commented Oct 29, 2014 at 20:05
  • You can also write your Comparator as an anonymous class, and use g and id directly if you make them final. Commented Oct 29, 2014 at 20:07

1 Answer 1

5

Build your own Comparator :

public MyComparator implements Comparator<Move>
{

    private Game game;
    private int id;

    public MyComparator(Game g, int id)
    {
         this.game = g;
         this.id = id;
    }

    // compare function, using game and I'd
 }

Use it like that :

 Move[] m = ... ;
Arrays.sort(m, new MyComparator(aGame, and));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.