java - 按字母顺序对列表中的元素进行排序

标签 java

<分区>

我有一个 Shape 类,在这个类中有一个名为 getRepr() 的方法可以获取形状的 char 表示.例如,

ShapeA.getRepr() ->'a' 
ShapeB.getRepr() ->'b'
ShapeC.getRepr() ->'c'

现在我有一个 ArrayList,它存储多个形状,包括 ShapeEShapeAShapeD ShapeCShapeB

问题是我如何使用 Collections.sort() 根据它们的 ArrayList按字母顺序 重新排列这些形状char 表示?

这个ArrayList排序后的预期结果应该是ShapeA, ShapeB, ShapeC, ShapeD, ShapeE.

或者有没有不用 Collections.sort() 就可以达到这个目的的方法?

最佳答案

你需要在你的父类(super class)中实现 Comparable 接口(interface)

public class MyClassSuperClass implements Comparable<MyClassSuperClass>{

    @Override
    public int compareTo(MyClassSuperClass o) {
        return this.getRepr().compareTo(o.getRepr());
    }


}

然后你可以在你的集合上调用 .sort 方法

  1. 如果 obj a>b compareTo 应返回一个值 > 0
  2. 如果对象a
  3. 如果 obj a == b compareTo 应返回 0

For the mathematically inclined, the relation that defines the natural ordering on a given class C is:

   {(x, y) such that x.compareTo(y) <= 0}.   The quotient for this total order is:
   {(x, y) such that x.compareTo(y) == 0}.   It follows immediately from the contract for compareTo that the quotient is an

equivalence relation on C, and that the natural ordering is a total order on C. When we say that a class's natural ordering is consistent with equals, we mean that the quotient for the natural ordering is the equivalence relation defined by the class's equals(Object) method: {(x, y) such that x.equals(y)}.

有关更多信息,请查看此链接:

https://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html

关于java - 按字母顺序对列表中的元素进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29811957/

相关文章:

java - 来自 Android 的 JSON 请求未执行

Java WebStart dll 未加载

java - JBOSS5中无法读取文件

java - 在虚拟 1024 核机器上测试 Java 程序

java - 在 KAFKA 中生成和使用 JSON

java - 默认情况在进入 switch-case 之前就被执行

java - 将用户的 OAuth2 token 放入 RestTemplate 中

java - java 获取文件的实际磁盘使用情况

java - 如何检查文本是否包含 IP 地址?

java - 独立的 war/java Web 应用程序