[英]Set have the same erasure, yet neither overrides the other error
My homework was to basically rewrite the methods for a set so it's usable for for a custom class I created called Square
. 我的工作是基本上重写集合的方法,以便将其用于我创建的名为Square
的自定义类。 I keep getting the error: 我不断收到错误:
error: name clash: removeAll(Collection<Square>) in SquareSet and removeAll(Collection<?>) in Set have the same erasure, yet neither overrides the other
public boolean removeAll(Collection<Square> objects) {
I imported both Set
and Collection
at the beginning of my code and the class SquareSet
implements Set<Square>
. 我在代码的开头导入了Set
和Collection
,并且SquareSet
类实现了Set<Square>
。
public boolean removeAll(Collection<Square> objects) {
Square[] newSet;
int count = 0;
for(Square each : objects) {
count -= 1;
newSet = new Square[(daSet.length)-count];
for (int i = 0; i < daSet.length; i++) {
if (daSet[i].equals(each)) {
if(i == 0) {
for (int j = 1; j < daSet.length ; j++) {
newSet[j - 1] = daSet[j];
}
} else if (i == ((daSet.length) - 1)) {
for (int j = 0; j < daSet.length ; j++) {
newSet[j] = daSet[j];
}
} else {
for (int j = 0; j < i; j++) {
newSet[j] = daSet[j];
}
for (int j = i; j < newSet.length; j++){
newSet[j] = daSet[j+1];
}
}
}
}
}
I understand a method is overloaded instead of overwritten when the parameter is different from the parameter type I'm overwriting. 我知道当参数与我要覆盖的参数类型不同时,方法会重载而不是被覆盖。 But I still don't understand why I'm getting this error. 但是我仍然不明白为什么会出现此错误。
Because you're implementing Set<Square>
, you'd naturally expect the removeAll
method to be removeAll(Collection<Square>)
, but unfortunately in the Set
interface, the removeAll
method is removeAll(Collection<?>)
, with a wildcard instead of the generic type parameter. 因为您正在实现Set<Square>
,所以您自然希望removeAll
方法为removeAll(Collection<Square>)
,但是不幸的是,在Set
接口中, removeAll
方法是removeAll(Collection<?>)
,且带有通配符而不是通用类型参数。 This causes your error -- Collection<Square>
is incompatible with Collection<?>
. 这将导致您的错误Collection<Square>
与Collection<?>
不兼容。
As for why it's that way, this question deals with that. 至于为什么会这样, 这个问题解决了。 Basically, the designers couldn't get it to work properly when the remove-like methods were fully generified. 基本上,当完全生成类似remove的方法时,设计师无法使其正常工作。
To implement the interface properly, you must have your parameter's type be Collection<?>
. 要正确实现接口,必须将参数的类型设置为Collection<?>
。 That means the type of each
must be Object
, and you'll have to type-check it to see if it's a Square
. 这意味着each
Object
的类型必须为Object
,并且必须对其进行类型检查以查看它是否为Square
。
In addition, you will want to size your new array more carefully, and only if you have a match to remove from your array. 此外,仅当您有匹配项要从阵列中删除时,才需要更仔细地调整新阵列的大小。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.