繁体   English   中英

奇怪的Java泛型编译错误:参数化方法不适用于相同的参数化类型?

[英]strange Java generics compilation error: parameterized method is not applicable for same parameterized types?

我偶然发现了这个错误,我找不到问题:

The method compute(Set<String>, Set<String>) 
in the type JaccardSimilarity<String> is not applicable 
for the arguments (Set<String>, Set<String>)

有问题的方法是使用泛型:

public class JaccardSimilarity<E> implements SimilarityMeasure<Set<E>, Set<E>> {

    @Override
    public double compute(Set<E> s1, Set<E> s2){
        // compute some stuff
    return unionSize == 0 ? 1 : intersectionSize / (double)unionSize;
    }
}

我在课堂上这样称呼它:

public MyClass {
    private JaccardSimilarity<String> sim = new JaccardSimilarity<String>();

    public void calc() {
    Set<String> s1 = new HashSet<>();
    s1.add("hallo welt");
    Set<String> s2 = new HashSet<>();
    s2.add("hallo welt");
            // the line below throws the error..
    double result = sim.compute(s1, s2);
    }

在我对Java泛型的简单理解中,这是完全有效的代码......

这怎么可能?

编辑 - 附加代码:

public interface SimilarityMeasure<Q, R> extends RelevanceFunction<Q, R> {}

和..

public interface RelevanceFunction<Q, R> {
    public double compute(Q v1, R v2);
}

编辑2:这是进口:

import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;

import <redacted>.JaccardSimilarity;

编辑3:这是错误:

import <redacted>.representation.Set;

微妙...

您可能正在导入不同的类。 SetString

仔细检查您的进口!

还要考虑使用Set<? extends E> 在您的实现中Set<? extends E> 那么E只需要是你使用的实际类型的超类型,如果它满足其他要求。

暂无
暂无

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

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