gpt4 book ai didi

Java:对具有两种类型的泛型类进行排序

转载 作者:搜寻专家 更新时间:2023-10-31 19:51:28 26 4
gpt4 key购买 nike

假设下面的泛型类有 2 个类型 T, U

public class Pair<T, U> implements Comparable<T, U>  { //Error 1

private final T first;
private final U second;

public Pair(T first_, U second_) {
first = first_;
second = second_;}

public T getFirst() { return first; }
public U getSecond() { return second; }
}

及其项目列表

List<Pair<Integer, Integer>> = new ArrayList<>() 

需要根据第一个/第二个属性进行排序。不幸的是,类定义包含一些问题,出现以下错误:

Error 1: wrong number of type arguments

如何设计比较器类?这段代码可能是完全错误的

public class SortBySecond implements Comparable <Pair <T, U>> {

public int compare(final Pair<T, U> p1, final Pair<T, U> p2) //Error 2
{
return t1.getSecond().compareTo(t2.getSecond()); //Updated comparator
}
}

Error 2 : Can not find symbols T, U, V

感谢您的帮助。

最佳答案

你的 Pair类应该实现 Comparable<Pair<T, U>>而不是 Comparable<T, U> ,这是一种不存在的类型。您还应该确保 TU具有可比性。

Comparator 中有很多有用的方法帮助您比较事物的界面。您可以使用它们来实现 Comparable<Pair<T, U>> .事实上,您不需要实现 Comparable对列表进行排序。你只需要创建一个 Comparator !

以下是如何实现 Comparable :

class Pair<T extends Comparable<T>, U extends Comparable<U>> implements Comparable<Pair<T, U>> {
public int compare(final Pair<T, U> p1, final Pair<T, U> p2)
{
// this first compares the first field. If the first fields are the same, the second fields are compared
// If you have a different requirement, implement it accordingly.
return Comparator.comparing(Pair::getFirst).thenComparing(Pair::getSecond).compare(p1, p2);
}
}

要对列表进行排序,请执行以下操作:

list.sort(Comparator.comparing(Pair::getFirst).thenComparing(Pair::getSecond));

要仅使用第二个字段对列表进行排序,请执行以下操作:

list.sort(Comparator.comparing(Pair::getSecond));

关于Java:对具有两种类型的泛型类进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57913205/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com