I would like an object to be comparable (to use it in a TreeSet in that case).
My object got a name field and I would like it to be sorted by alphabetical order.
I thought first that I could use the unicode value of the string and simply do a subtraction, but then AA would be after Ab for example…
Here’s how I started :
public final class MyObject implements Comparable<MyObject> {
private String name;
public MyObject(String name) {
this.name = name;
}
public String name() {
return name;
}
@Override
public int compareTo(MyObject otherObject) {
return WHAT DO I PUT HERE ?;
}
}
Thanks to those who will help, have a nice day!
You are overthinking the problem. String
s have their own natural ordering, which is alphabetic, so you can just use the String.compareTo
like this:
@Override
public int compareTo(MyObject otherObject) {
return this.name.compareTo(otherObject.name);
}