Java 实现 Comparable 以获取字符串的字母排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22871583/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 18:35:24  来源:igfitidea点击:

Implements Comparable to get alphabetical sort with Strings

javainterfacecomparableimplementsalphabetical-sort

提问by Silver Duck

I would like an object to be comparable (to use it in a TreeSet in that case).

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

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…

我首先想到我可以使用字符串的 unicode 值并简单地做一个减法,但是 AA 将在 Ab 之后,例如……

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!

感谢那些愿意提供帮助的人,祝你有美好的一天!

采纳答案by azurefrog

You are overthinking the problem. Strings have their own natural ordering, which is alphabetic, so you can just use the String.compareTolike this:

你把问题想得太多了。 Strings 有自己的自然顺序,按字母顺序排列,所以你可以String.compareTo像这样使用:

@Override
public int compareTo(MyObject otherObject) {
    return this.name.compareTo(otherObject.name);
}

回答by Marco Acierno

return name.compareTo(otherObject.name);

String already implements Comparableso you don't need do to anything.

String 已经实现,Comparable所以你不需要做任何事情。

回答by Leo

I think you want something like this

我想你想要这样的东西

package mine;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class MyObject {
    private String name;

    public MyObject(String name) {
        this.name = name;
    }

    public MyObject() {
        // TODO Auto-generated constructor stub
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }



    @Override
    public String toString() {
        return "MyObject [name=" + name + "]";
    }

    public static void main(String[] args){
        List<MyObject> l = new ArrayList<>();
        l.add(new MyObject("Ab"));
        l.add(new MyObject("AA"));
        l.add(new MyObject());

        Collections.sort(l, new Comparator<MyObject>(){

            @Override
            public int compare(MyObject o1, MyObject o2) {
                if (o1.name == null && o2.name == null){
                    return 0;
                }else if (o1.name == null){
                    return -1;
                }else if (o2.name == null){ 
                    return 1;
                }else{
                    return o1.name.toUpperCase().compareTo(o2.name.toUpperCase());
                }
            }

        });

        System.out.println(l);
    }
}

回答by Musa

Exist so many way which preferred before it. But for maintain better compatibility, performance and avoiding runtime exceptions (such as NullPointerException) use best practices which is

存在着许多在它之前更喜欢的方式。但是为了保持更好的兼容性、性能和避免运行时异常(例如 NullPointerException),请使用最佳实践

For String

对于字符串

@Override
    public int compareTo(OtherObject o) {
        return String.CASE_INSENSITIVE_ORDER.compare(this.name,o.name);
    }

For int, double float (to avoid boxing and unboxing which issue for performance use below comparators)

对于 int,双浮点数(为了避免装箱和拆箱这在比较器下面的性能使用问题)

// with functional expression
Comparator.compareInt, Comparator.compareDouble, Comparator.compareFloat


// or with static compare method
/**
*  Integer
*/
public int compareTo(Integer anotherInteger) {
        return compare(this.value, anotherInteger.value);
    }

/**
*  Double
*/
public int compareTo(Double anotherDouble) {
        return Double.compare(value, anotherDouble.value);
    }

/**
*  Float
*/
public int compareTo(Float anotherFloat) {
        return Float.compare(value, anotherFloat.value);
    }

/**
*  Objects
*/
public int compareTo(Object other) {
        return Object.compare(value, other.value);
    }

[Effective Java Item 14: Consider implement Comparable]

[Effective Java Item 14: 考虑实现 Comparable]

Finally, whenever you implement a value class that has a sensible ordering, you should have a class implements Comparable interface so that its instances can be easily sorted, searched and used in comparison-based collections. When comparing field values in the implementations of the compareTo methods, avoid the use of the < and > operators. Instead, use the static compare methods in the boxed primitive classes or the comparator construction methods in the Comparator interface

最后,每当你实现一个具有合理排序的值类时,你应该让一个类实现 Comparable 接口,以便它的实例可以很容易地排序、搜索和在基于比较的集合中使用。在 compareTo 方法的实现中比较字段值时,避免使用 < 和 > 运算符。相反,使用装箱基元类中的静态比较方法或 Comparator 接口中的比较器构造方法