我的排序测试应用程序有问题,我使用比较器。 我收到了一条消息:
线程“main”中的异常java.lang.Error:未解决的编译问题: 无法推断Sorter<>
的类型参数
对于该代码:
public class TestClass {
public static void main(String[] args){
Sorter<Person> idSorter = new Sorter<>(new idComparator());
.
.
.
}
}
分拣机类:
public class Sorter<T extends Comparable> {
Comparator<T> comparator;
int switches = 0,
compares = 0;
public Sorter(Comparator<T> comparator) {
this.comparator = comparator;
}
public Sorter() {
this.comparator = null;
}
protected int compare(T first, T second) {
if (this.comparator == null) {
int cmp = first.compareTo(second);
this.compares++;
return cmp;
}
可比较的界面:
public interface Comparable {
public int compareTo(Comparable other);
}
idComparator类:
public class idComparator implements Comparator<Integer> {
public int compare(Integer first, Integer second) {
return first > second? 1: first == second? 0: 1;
}
}
比较器界面:
public interface Comparator<T> {
int compare(T first, T second);
}
这样的使用有什么问题?我怎样才能做得更好?
答案 0 :(得分:3)
在这一行:
Sorter<Person> idSorter = new Sorter<>(new idComparator());
idComparator
实现了Comparator<Integer>
,因此T
的{{1}}为Sorter
,但您的声明指示编译器的 { {1}}是Integer
,因此编译器会混淆并发出消息。
T
但有些人在评论中说,基于某个整数对人进行排序是奇数。
另请注意:
Person
Sorter<Integer> idSorter = new Sorter<>(new idComparator());
语句
return
名称应以大写字母开头:Sorter#compare
idComparator
/ IdComparator
,你应该用其他名称命名(Comparable
?)Comparator
,这与java混淆了的。答案 1 :(得分:0)
为什么不使用Java 8进行排序和比较?为了澄清,Lists.newArrayList是Google Guava集合。
public void sortingEntitiesById() {
List<Person> persons = Lists.newArrayList(new Person("Sarah", 10), new Person("Jack", 12));
persons.sort((h1, h2) -> h1.getId().compareTo(h2.getId()));
Assert.assertThat(persons.get(0), equalTo(new Person("Sarah", 10)));
}
反向排序
public void sortingEntitiesByIdReversed() {
List<Person> persons = Lists.newArrayList(new Person("Sarah", 10), new Person("Jack", 12));
Comparator<Person> comparator = (h1, h2) -> h1.getId().compareTo(h2.getId());
persons.sort(comparator.reversed());
Assert.assertThat(persons.get(0), equalTo(new Person("Jack", 12)));
}
按多个条件排序
public void sortEntitiesWithMultipleConditions() {
List<Person> persons = Lists.newArrayList(
new Person("Sarah", 12), new Person("Sarah", 10), new Person("Zack", 12));
persons.sort(Comparator.comparing(Person::getName).thenComparing(Person::getId));
Assert.assertThat(persons.get(0), equalTo(new Person("Sarah", 10)));
}