比较器作为类构造函数的参数



我似乎在任何地方都找不到确切的方法。我正在编写一个类,该类将比较器作为类构造函数的参数/参数。我想用它来对列表中的项目进行排序。但我不确定如何处理新类中的比较器。

  • 我已导入java.util.Comparator
  • 在类声明中,我说"impements Comparator<T>">
  • 我已经写了(Comparator<T> c(作为类的构造函数的参数。

我从来没有以这种方式使用过比较器 - 我将其用作内部类,仅此而已,因此当我将比较器作为构造函数的参数时,我不确定如何使比较方法在此类中工作。

我做过的唯一一件事是上面的三个项目符号项目。每当我尝试使用比较器作为参数时,都会收到一条错误消息。

下面是构造函数的代码:

public class SortedList<T> implements Comparator<T>
//value, position and array are instance variables
//I am switching array to a List to deal with generics
private int position;
private Integer[] array;
public SortedList(Comparator<T> c){
this.position = 0;
this.array = new Integer[25];
}
public void sort(Integer num){
boolean valid = false;
int i = 0;
while(!valid && i < array.length-1){
if(num.compareTo(array[i] > 0)){
array[i+1] = array[i];
array[i] = num;
}else{
i++;
}
}

我收到的错误消息是:

  • 找不到符号 - 方法比较到

我希望能够比较任何两个对象,而不仅仅是整数,这就是为什么我想将比较器作为参数。

从您的问题中不清楚,但您的代码段中唯一的集合式结构是整数对象数组。因此,这里唯一要排序的理智的事情是该数组。

您需要一个Comparator<Integer>来对其进行排序,而不是Comparator<T>

一旦你有了它,要对数组进行排序,你需要做的就是..

Arrays.sort(array, c);

SortedList<T>类不得实现Comparator<T>接口,因为此类不用于比较对象。但是,它将使用给定的Comparator<T>实例对其条目进行排序。这意味着类和方法应具有以下定义:

public class SortedList<T> {
// ...
}

该类不再实现Comparator<T>接口。

private T[] array;

array字段应为T[]类型,因为此SortedList<T>对象用于排序/保存类型为T的对象,而不是Integer对象。

public SortedList(Comparator<T> c){
// ...
this.comparator = c;
}

没错。构造函数接收Comparator<T>实例。应将此引用存储到字段,以便以后可以在sort()方法中使用它。

public void sort(){
// ...
}

sort()方法上的Integer参数没有任何意义,因此请将其删除。现在,您可以在sort()方法中使用存储的Comparator<T>实例,并调用其compare()方法来比较存储数组中的两个对象。代码片段可能如下所示:

// ...
if (this.comparator.compare(this.array[i], this.array[i+1])) {
// it should be on the left
} else {
// it should be on the right
}
// ...

相关内容