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?

NovaCaller
  • 67
  • 1
  • 1
  • 5
  • 1
    You need `Collections.sort()` rather than `Arrays.sort()`. – daniu Dec 03 '18 at 15:06
  • Possible duplicate of [Sort ArrayList of custom Objects by property](https://stackoverflow.com/questions/2784514/sort-arraylist-of-custom-objects-by-property) – LuCio Dec 03 '18 at 15:11

3 Answers3

3

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

Collections.sort(moveList, new myComp());
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
1

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

moveList.sort(Comparator.comparingDouble(CoolMove::getValue));
Naman
  • 27,789
  • 26
  • 218
  • 353
0

Sort the list (JDK 8.0)

moveList.sort(new myComp());
forpas
  • 160,666
  • 10
  • 38
  • 76