【问题标题】:generic class that implements comparable实现可比较的泛型类
【发布时间】:2021-02-01 13:59:36
【问题描述】:

我被分配了一个问题:编写一个通用的 WeightedElement 类,它存储一个 E 类型的元素和 W 类型的权重。它应该依靠 W 的 compareTo() 实现 Comparable。您应该强制 W 本身具有可比性。

到目前为止,我已经制作了类并实现了可比性,但是在为 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;
        }
    }
}

我遇到的问题是,当我比较权重时,找不到数据的权重。还有我必须创建的任何其他方法才能正确地拥有一个在其中一个变量上实现可比较的类吗?感谢您的帮助

【问题讨论】:

  • 根据您的分配,您的 WeightedElement 应该实现 Comparable。然后,让它依赖于 W 的可比性,编写一个简单的代理函数,如 public int compareTo(WeightedElement&lt;E,W&gt; data) { return this.weight.compareTo(data.weight); }

标签: java generics comparator bluej


【解决方案1】:

您拥有正确的泛型,但就像WeightedElement 本身一样,您必须在权重上调用compareTo - 您不能使用&lt;== 进行比较。

【讨论】:

    【解决方案2】:
    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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-06
      • 2023-03-19
      • 1970-01-01
      • 2012-11-16
      • 1970-01-01
      • 2011-04-27
      • 1970-01-01
      相关资源
      最近更新 更多