java - 实现java接口(interface)并使用泛型

标签 java generics interface

我有一个名为 BST(二叉搜索树的缩写)的 java 接口(interface),它具有泛型类型 Key,Value,其中 Key 扩展了 Comparable。我将其定义如下。

public interface BST<Key extends Comparable<Key>,Value> {

    public void put(Key key,Value value);

    public Value get(Key key);

    public void delete(Key key);

    public Iterable<Key> keys();

}

现在我想定义上述接口(interface)的实现。我尝试了这个

public class BSTImpl<Key extends Comparable<Key> ,Value>  implements BST<Key extends Comparable<Key>,Value> {

... 

}

上面的定义会导致 eclipse IDE 中出现错误消息..extends implements BST<Key 之后的 token 看来是罪魁祸首

Syntax error on token "extends", , expected

如果我从定义中省略“extends”标记(如下所示),错误就会消失,并且我可以让 Eclipse 正确生成未实现的方法

public class BSTImpl<Key extends Comparable<Key> ,Value>  implements BST<Key ,Value> {
    @Override
    public void put(Key key, Value value) {
        // TODO Auto-generated method stub          
    }
    @Override
    public Value get(Key key) {
        // TODO Auto-generated method stub
        return null;
    }
    @Override
    public void delete(Key key) {
        // TODO Auto-generated method stub          
    }
    @Override
    public Iterable<Key> keys() {
        // TODO Auto-generated method stub
        return null;
    }
}

为什么扩展标记首先会导致错误?有人可以解释一下吗?

最佳答案

因为

public class BSTImpl<Key extends Comparable<Key> ,Value>  implements BST<Key extends Comparable<Key>,Value> {
                    ^ type declaration                                   ^ type argument

在类声明中,泛型类型是类型声明,您可以稍后在类主体中重用它。在您正在实现的接口(interface)中,它是一个类型参数参数。换句话说,你是说我的类用这种类型实现了这个接口(interface)。你必须给它一个特定的类型。说 Key extends Comparable... 作为类型参数是没有意义的。

Java Language Spec has more details

The type parameter section follows the class name and is delimited by angle brackets.

以及 the section for Superclasses

If the TypeDeclSpecifier is followed by any type arguments, it must be a correct invocation of the type declaration denoted by TypeDeclSpecifier, and none of the type arguments may be wildcard type arguments, or a compile-time error occurs.

关于java - 实现java接口(interface)并使用泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19229453/

相关文章:

generics - 比较通用结构类型

java - Java : a design problem 中具有泛型类型的抽象工厂

c++ - 我可以像这样混合使用 pimpl 和 C 接口(interface)吗?

java - javadoc 注释中接口(interface)方法的标签?

java - 如何在 servlet 中创建 URL?

java - 为什么这段 Scala 代码会在运行时抛出 IllegalAccessError?

c# - 不允许重载泛型类型参数?

java - 使用 Web 服务在 Java 中调用 C#.Net 函数

java - 延迟初始化异常 : load lazy attribute from a session different from the original one in Hibernate

java - 接口(interface) : profit of using