创建四个不同的比较器

Creating four different comparators

如何创建 2 个不同的比较器来对 2 个 ArrayList 进行排序? 第一个列表按行号排序,然后按列号排序。

[(0,1,A), (1,1,A), (1,2,A), (2,1,A)]  // Longest sequence of row-adjacent elements has size 2

第二个列表先按列号再按行号排序。

[(0,1,A), (1,1,A), (2,1,A), (1,2,A)]  // Longest sequence appears as adjacent elements, size 3

我有 ArrayList<RowColElem<T>> rowElems 必须先按行号排序,然后按列号排序; ArrayList<RowColElem<T>> colElems 必须先按列号排序,然后按行号排序。注意:两个数组列表都包含相同的元素但未排序(即按添加顺序排列),我必须对其进行排序但不知道如何实现 2 个比较器。我应该如何创建 2 个比较器?

public class Board{
   ..............
..................
ArrayList<<T>> rowsElems; //Already contains information
ArrayList<<T>> colsElems; //Already contains information

public List<m<T>> ColOrder(){
      //needs to sort rowElems 
  }

  public List<<T>> elementsInColRowOrder(){
      //needs to sort colElems 
  }

}

第一个比较器:

public class CompareRowCol<T> implements Comparator<RowColElem<T>> {
    public int compare(RowColElem<T> o1, RowColElem<T> o2) {
        int cmp = Integer.compare(o1.getRow(),o2.getRow());
        if(cmp != 0) {
            return cmp;
        } else {
            return Integer.compare(o1.getCol(),o2.getCol());
        }
    }
}

第二次,您只需将 getRowgetCol 交换:

public class CompareColRow<T> implements Comparator<RowColElem<T>> {
    public int compare(RowColElem<T> o1, RowColElem<T> o2) {
        int cmp = Integer.compare(o1.getCol(),o2.getCol());
        if(cmp != 0) {
            return cmp;
        } else {
            return Integer.compare(o1.getRow(),o2.getRow());
        }
    }
}

此列优先于行。

您可以使用 Collections.sort 方法对列表进行排序:

Collections.sort(rowsElems,new CompareRowCol<T>());//create new comparator and sort

这将改变 rowElems,使其元素在调用后排序。

但是建议不要使用包含相同数据的两个列表,因为这会使两者之间保持一致变得更加困难。使用一个列表,然后对其进行克隆和排序。

说明

我只解释第一个比较器,因为另一个是它的对偶,类比很容易。

首先我们比较两个给定项目的两行:

int cmp = Integer.compare(o1.getRow(),o2.getRow());

cmp为整数,如果o1行号小于o2行号则为负数;如果两个数字相等则为零;如果 o1 的行号大于 o2 的行号,则为正数。

接下来我们执行检查:

if(cmp != 0)

如果cmp 等于0,这意味着两个行号相等,因此我们必须测试列号。但是,如果 cmp 不等于零,则行号不同,因此我们可以立即 return 结果 cmp.

现在如果两个行号相等,我们对列号进行比较:

return Integer.compare(o1.getCol(),o2.getCol());

我们可以立即return结果,因为如果两个列号相等,则这两个项目也被认为是相等的。