Here is the question:
这是一个问题:
Java sort based on two columns
Java排序基于两列
But, can anyone explain how to do without using Comparator? In other words, How the comparator works internally for sorting multiple columns?
但是,任何人都可以解释如何不使用比较器吗?换句话说,比较器如何在内部工作以排序多个列?
1 个解决方案
#1
0
The sort method must have some way of finding out the relative order of pairs of rows. There are two supported ways of doing it using the normal sorts. Either use instances of a class that implements Comparable to represent rows, or use a Comparator.
sort方法必须有某种方法来找出行对的相对顺序。使用常规排序有两种支持的方法。使用实现Comparable的类的实例来表示行,或者使用Comparator。
If you don't want to do either of those, you would have to write your own, specialized, sort method. When it needs to compare two rows, it would look first at the higher priority column. If the rows differ in that column, that gives there order. If they are equal in that column, order them based on the second column.
如果你不想做其中任何一个,你必须编写自己的,专门的排序方法。当需要比较两行时,它首先会看到更高优先级的列。如果该列的行不同,则会给出顺序。如果它们在该列中相等,则根据第二列对它们进行排序。
That said, using a standard sort with either Comparable rows or a Comparator is much better than mixing up the sort logic and the comparison logic. Comparator is the more flexible way.
也就是说,使用带有Comparable行或Comparator的标准排序比混合排序逻辑和比较逻辑要好得多。比较器是更灵活的方式。
#1
0
The sort method must have some way of finding out the relative order of pairs of rows. There are two supported ways of doing it using the normal sorts. Either use instances of a class that implements Comparable to represent rows, or use a Comparator.
sort方法必须有某种方法来找出行对的相对顺序。使用常规排序有两种支持的方法。使用实现Comparable的类的实例来表示行,或者使用Comparator。
If you don't want to do either of those, you would have to write your own, specialized, sort method. When it needs to compare two rows, it would look first at the higher priority column. If the rows differ in that column, that gives there order. If they are equal in that column, order them based on the second column.
如果你不想做其中任何一个,你必须编写自己的,专门的排序方法。当需要比较两行时,它首先会看到更高优先级的列。如果该列的行不同,则会给出顺序。如果它们在该列中相等,则根据第二列对它们进行排序。
That said, using a standard sort with either Comparable rows or a Comparator is much better than mixing up the sort logic and the comparison logic. Comparator is the more flexible way.
也就是说,使用带有Comparable行或Comparator的标准排序比混合排序逻辑和比较逻辑要好得多。比较器是更灵活的方式。