I have a class, Word, that has a String representing a word and an Enum representing the difficulty of the word. Then I have another class, Vocab, that has an ArrayList of Word-objects. I want to sort my ArrayList by either difficulty or by the alphabetical order of the word.
I figured I should use a Comparator, and here is how I did it. All classes are in the same package:
Diff:
public enum Diff {
EASY, MEDIUM, HARD;
}
Word:
public class Word {
private String word;
private Diff diff;
public Word(String word, Diff diff) {
this.word = word;
this.diff = diff;
}
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
public Diff getDiff() {
return diff;
}
public void setDiff(Diff diff) {
this.diff = diff;
}
@Override
public String toString() {
String string = getWord() + ", " + getDiff();
return string;
}
}
Vocab:
public class Vocab {
private ArrayList<Word> words;
public Vocab() {
words = new ArrayList<>();
}
public void sortByPrio() {
Collections.sort(words, prioCompare);
}
public void sortByName() {
Collections.sort(words, nameCompare);
}
private Comparator<Word> prioCompare = new Comparator<Word>() {
@Override
public int compare(Word w1, Word w2) {
return (w1.getDiff().ordinal() - w2.getDiff().ordinal());
}
};
private Comparator<Word> nameCompare = new Comparator<Word>() {
@Override
public int compare(Word w1, Word w2) {
return (w1.getWord().compareToIgnoreCase(w2.getWord()));
}
};
public void addWord(Word newWord) {
words.add(newWord);
}
@Override
public String toString() {
String string = words.toString();
return string;
}
}
Main:
public class Main {
public static void main(String[] args) {
Vocab myWords = new Vocab();
myWords.addWord(new Word("Apple", Diff.EASY));
myWords.addWord(new Word("Besmirch", Diff.MEDIUM));
myWords.addWord(new Word("Pulchritudinous", Diff.HARD));
myWords.addWord(new Word("Dog", Diff.EASY));
System.out.println(myWords);
myWords.sortByPrio();
System.out.println(myWords);
}
}
Is anything inherently wrong with my code above, regarding my implementation of the Comparator? If so, what should I improve? Also, I haven't redefined equals, which I usually do when I implement Comparable. Should I redefine it now as well?