You got an error because when you call Collections.sort() , passing only the List<T> as parameter, it expects the list items to implement the Comparable interface. Since this is not the case with CreateShape , sort() has no way of knowing how these objects should be sorted.
Here are two options you should consider:
CreateShape can implement Comparable<CreateShape> : do this if you think that CreateShape instances have a natural order in which they should be sorted. If you want to sort by char field, for example:
class CreateShape implements Comparable<CreateShape> { private char displayChar; public char getDisplayChar() { return displayChar; } @Override public int compareTo(CreateShape that) { return Character.compare(this.displayChar, that.displayChar); } }
Then you can just call Collections.sort() :
Collections.sort(shapes);
Create a custom Comparator<CreateShape> : do this if you want to sort CreateShape instances arbitrarily. You may have a Comparator that sorts by name, another that sorts by id, etc. Example:
enum DisplayCharComparator implements Comparator<CreateShape> { INSTANCE; @Override public int compare(CreateShape s1, CreateShape s2) { return Character.compare(s1.getDisplayChar(), s2.getDisplayChar()); } }
Then you should call Collections.sort() , passing the comparator as a parameter:
Collections.sort(shapes, DisplayCharComparator.INSTANCE);
Note. I implemented DisplayCharComparator as a single line. This is because it has no state, so there is no need to have more than one instance of this comparator. An alternative is to use a static variable:
class CreateShape { static final Comparator<CreateShape> DISPLAY_CHAR_COMPARATOR = new DisplayCharComparator(); static class DisplayCharComparator implements Comparator<CreateShape> { ... }
Or, if you are using Java 8, you can use Comparator.comparing :
shapes.sort(Comparator.comparing(CreateShape::getDisplayChar));
source share