简体   繁体   English

实现可比较的泛型类

[英]generic class that implements comparable

I have been assigned the problem: Write a generic WeightedElement<E,W> class which stores an element of type E and a weight of type W. It should implement Comparable relying on W's compareTo().我被分配了一个问题:编写一个通用的 WeightedElement<E,W> 类,该类存储类型为 E 的元素和类型为 W 的权重。它应该依赖 W 的 compareTo() 实现 Comparable。 You should enforce that W itself is comparable.您应该强制 W 本身具有可比性。

So far I have made the class and implemented comparable but am encountering issue when making the compareTo() method for W. I have:到目前为止,我已经制作了该类并实现了可比性,但在为 W 制作 compareTo() 方法时遇到了问题。我有:

public class WeightedElement<E, W extends Comparable<W>> {

    public E element;
    public W weight;


    public WeightedElement() {
        element = this.element;
        weight = this.weight;
    }

    public int compareTo(W data) {
        if (this.weight == data.weight) {
            return 0;
        } else if (this.weight < data.weight) {
            return 1;
        } else {
            return 1;
        }
    }
}

I am encountering the issue that when I compare the weights, the weight for data is not found.我遇到的问题是,当我比较权重时,找不到数据的权重。 Also are there any other methods I have to create to properly have a class that implements comparable on one of the variables?还有我必须创建的任何其他方法才能正确地拥有一个在其中一个变量上实现可比性的类吗? Thank you for any help感谢您的任何帮助

您拥有正确的泛型,但就像WeightedElement本身一样,您必须对权重调用compareTo —— 不能使用<==进行比较。

public class WeightedElement<E, W extends Comparable<W>> implements Comparable<WeightedElement<E, W>> {

    private final E element;
    private final W weight;

    public WeightedElement(E element, W weight) {
        this.element = element;
        this.weight = Objects.requireNonNull(weight, "'weight' should not be null");
    }

    @Override
    public int compareTo(WeightedElement<E, W> other) {
        return other == null ? 1 : weight.compareTo(other.weight);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM