Implements Comparable to get alphabetical sort with Strings

Silver Duck picture Silver Duck · Apr 4, 2014 · Viewed 20.6k times · Source

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!

Answer

azurefrog picture azurefrog · Apr 4, 2014

You are overthinking the problem. Strings 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);
}