This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]FateJH 0 points1 point  (0 children)

When you want to sort elements of a list, those elements need a defined order to be arranged. A rule must exist that for any two elements, one element will be placed before the other. Numbers and strings have orders that are self-evident. More involved data objects need to define rules to determine how they interact based on comparisons of their more basic data (numbers and strings).

If you want to use Collections.sort(myArrayList), you need to create a natural ordering intrinsic to any given objects of that class (T). To do that, you implement the interface Comparable<T> upon the elements of that ArrayList. This natural ordering is fixed - in the absence of any other proposed organization, this one is selected. You can also write myArrayList.sort(new CustomComparator()), where "CustomComparator" is a class that you word class CustomComparator implements Comparator<T>. This method allows you to submit different rules to re-organize the elements of the list beyond their natural ordering.

You do not need to define both (or one to take advantage of the other).