2

I have an ArrayList containing CoolMove elements and want to sort it by the values CoolMove.getValue() returns (these values are Doubles). I read that you can sort using a comparator class and in an attempt to do this I made the following:

I have 2 classes, one having these code lines:

ArrayList<CoolMove> moveList = getMoves();
Arrays.sort(fishMoves, new myComp());

My 2nd class is this comparator:

class myComp implements Comparator<CoolMove> {

    @Override
    public int compare(CoolMove move1, CoolMove move2) {
        return Double.compare(move1.getValue(), move2.getValue());
    }
}

My problem is that at Arrays.sort I get this error: The method sort(T[], Comparator) in the type Arrays is not applicable for the arguments (ArrayList, myComp) How can I fix this?

2
  • 1
    You need Collections.sort() rather than Arrays.sort(). Commented Dec 3, 2018 at 15:06
  • Possible duplicate of Sort ArrayList of custom Objects by property Commented Dec 3, 2018 at 15:11

3 Answers 3

3

moveList is a list not an array, use the sort method from Collections:

Collections.sort(moveList, new myComp());
Sign up to request clarification or add additional context in comments.

Comments

1

You can simplify all of it using List.sort​(Comparator<? super E> c)as:

moveList.sort(Comparator.comparingDouble(CoolMove::getValue));

Comments

0

Sort the list (JDK 8.0)

moveList.sort(new myComp());

1 Comment

worth saying, this is only available as of JDK8

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.