Implements Comparable to get alphabetical sort with Strings

后端 未结 4 897
离开以前
离开以前 2021-02-20 14:30

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.

4条回答
  •  一整个雨季
    2021-02-20 15:01

    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);
    }
    

提交回复
热议问题