英文:
generic class that implements comparable
问题
以下是翻译好的部分:
我被分配了这个问题:编写一个通用的 WeightedElement<E, W> 类,它存储了一个类型为 E 的元素和一个类型为 W 的权重。它应该实现 Comparable 接口,依赖于 W 的 compareTo() 方法。你应该强制要求 W 本身是可比较的。
到目前为止,我已经创建了这个类并实现了 Comparable 接口,但是在为 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;
}
}
}
我遇到的问题是,在比较权重时,无法找到 data 的权重。此外,我是否需要创建其他方法来正确地实现一个在其中一个变量上实现了 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(). You should enforce that W itself is comparable.
So far I have made the class and implemented comparable but am encountering issue when making the compareTo() method for W. I have:
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
答案1
得分: 1
你已经理解了泛型部分,但是和 WeightedElement
本身一样,你需要在权重上调用 compareTo
方法 —— 不能使用 <
或者 ==
来进行比较。
英文:
You have the generics right, but just like WeightedElement
itself, you have to call compareTo
on the weights -- you can't use <
or ==
to do comparisons.
答案2
得分: 0
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);
}
}
英文:
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);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论