我有一个 Shape
类,在这个类中有一个名为 getRepr()
的方法可以获取形状的 char
表示.例如,
ShapeA.getRepr() ->'a'
ShapeB.getRepr() ->'b'
ShapeC.getRepr() ->'c'
现在我有一个 ArrayList
,它存储多个形状,包括 ShapeE
、ShapeA
、ShapeD
、 ShapeC
和 ShapeB
。
问题是我如何使用 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 方法
- 如果 obj a>b compareTo 应返回一个值 > 0
- 如果对象a
- 如果 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