You speak of custom comparators...directly comparing the contents of the arrays using String methods would probably be a more straightforward solution. However, for the purposes of academics, using a custom comparator means using a class to solve your problem. Creating a custom comparator in Java requires that you implement the Comparable
interface. All this really means is that your class will need to implement the method compareTo
method:
class MyClass implements Comparable {
...
@Override
public int compareTo(Object o) {
...
}
}
When you override compareTo
, you decide what makes an object "greater" or "less than" another object. If an object is "greater" than another object, your custom method should return 1. If it is "less than" another object, it should return -1. If it is equal, it should return 0. Being "greater" or "less than" indicates how objects should be sorted.
From what I can tell, the elements in your order
array match the beginning of elements it would be called upon to help sort, e.g. "Paperclip 1"
starts with "Paperclip"
. Assuming that is true, an appropriate compareTo
method could use startsWith
to make decisions about the appropriate order:
class MyClass implements Comparable {
private static final String order[] = {"Paperclip", "Pencil", "Earphones", "Pen"};
private String value;
...
@Override
public int compareTo(Object o) {
MyClass that = (MyClass)o;
int thisRank = 0;
int thatRank = 0;
for (String ord : order) {
if (this.value.startsWith(ord)) {
thisRank = count;
}
if (that.value.startsWith(ord)) {
thatRank = count;
}
count++;
}
if (thisRank > thatRank) return 1;
if (thisRank < thatRank) return -1;
return 0;
}
}
You would then need to create some kind of collection with your new class and then sort it:
MyClass displayList[] = { new MyClass("Pencil 1"), new MyClass("Pen 1"),
new MyClass("Dog 1"), ... }
Arrays.sort(displayList);
or
TreeSet<MyClass> displayList = new TreeSet<>();
displayList.add(new MyClass("Pencil 1"));
displayList.add(new MyClass("Pen 1"));
...
Arrays.sort
employs your compareTo
method to properly sort the array. TreeSet
does the same; it just calls compareTo
every time you insert a new element.