Implements Comparable to get alphabetical sort with Strings

后端 未结 4 2256
你的背包
你的背包 2021-02-20 14:04

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 14:47

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

提交回复
热议问题