为什么我不能为此代码使用Collections.max()函数?-Java

Tay*_*rie 3 java sorting generics collections comparator

我有十棵树。每棵树都有一些实例变量(空间,网格,适用性和ID);在地理空间和网格上的位置,分别表示从0到1的栖息地适用性的值,以及一个ID号。

我将这些树及其关联的数据放到一个称为树的ArrayList中。然后,我让系统打印出它们的ID和相关的适用性值。代码如下。

最后,我想打印出最高的适用性值,但在max提示下始终出现错误:

“边界不匹配:max(Collection<? extends T>)类型的通用方法Collections不适用于参数(ArrayList<Trees>)。推断的类型Trees不是边界参数的有效替代品<T extends Object & Comparable<? super T>>

我似乎无法弄清楚这意味着什么。如果您需要查看更多代码,请告诉我。

有谁知道我如何获得最高适用性值(最接近1的值)?

int treeCount = 10;
for (int i = 0; i < treeCount; i++) {
    double suitability = RandomHelper.nextDoubleFromTo(0, 1);
    int id = i;
    context.add(new Trees(space, grid, suitability, id));

    ArrayList<Trees> trees = new ArrayList<Trees>();

    Trees tree;

    tree = new Trees(space, grid, suitability, id);
    trees.add(tree);
    System.out.println("Tree " + id + " has a suitability of " + suitability);

    Object obj = Collections.max(trees);
    System.out.println(obj);
}
Run Code Online (Sandbox Code Playgroud)

Neu*_*ron 5

您可能已经忘记实现Comparable<T>..如果不这样做,就无法分辨哪棵树是“最大的”。

您可能想要这样做:

public class Tree implements Comparable<Tree> {
    @Override
    public int compareTo(Tree o) {
        // use the value which should be used for comparison instead of getSuitability().
        // remember: here you have private access to object o. if your value is not a
        // double, there is also a Integer.compare(..) function, but you could also just
        // return value - other.value..
        return Double.compare(getSuitability(), o.getSuitability());
    }
    // .. code ..
}
Run Code Online (Sandbox Code Playgroud)

如果您无法修改Tree该类,则始终可以实现Comparator<Tree>

public class TreeComparator implements Comparator<Tree> {
    @Override
    public int compare(Tree o1, Tree o2) {
        return Double.compare(o1.getSuitability(), o2.getSuitability());
    }
}
Run Code Online (Sandbox Code Playgroud)

并将其与Collections.max(Collection, Comparator)功能一起使用:

Tree maxTree = Collections.max(trees, new TreeComparator());
Run Code Online (Sandbox Code Playgroud)

如果您经常调用此代码,请考虑将new TreeComparator()调用提取为常量。