实现Comparable以使用字符串按字母顺序排序 [英] Implements Comparable to get alphabetical sort with Strings

查看:220
本文介绍了实现Comparable以使用字符串按字母顺序排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望对象具有可比性(在这种情况下,可在TreeSet中使用它。)

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.

我首先认为我可以使用字符串的unicode值并简单地进行减法,但是例如,AA会在Ab之后。

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…

这是我的开始方式:

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!

推荐答案

您正在思考这个问题。 String 具有它们自己的自然顺序,即字母顺序,因此您可以像这样使用 String.compareTo

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

这篇关于实现Comparable以使用字符串按字母顺序排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆