繁体   English   中英

具有用于实例化其他通用接口的通用类型参数的Java类

[英]Java class with a generic type parameter that instantiates a different generic interface

我发现了一些关于Java局限性的问题 ,即不能使用不同类型的参数两次实现相同的接口。 (例如,您不能是Iterable<String>Iterable<Integer> ),但是我没有发现有关以下情况的任何讨论。

我可以说

    public class A implements Iterable<Integer> {    
        public Iterator<Integer> iterator() {
            throw new UnsupportedOperationException();
        }
    }

我可以说

    public class A<T> {
        T getFoo() { 
            throw new UnsupportedOperationException();
        }
        void setFoo(T foo) { 
            throw new UnsupportedOperationException();
        }
    }

但是我不清楚为什么不允许以下内容。 [请参阅下面的更正。]第一种情况似乎已经从A的通用规范中“删除”了Integer类型(在情况1中,我不必说A<Integer> 。)那么为什么我们不能给出像这样的新型T?

    public class A<T> implements Iterable<Integer> {
        T getFoo() { 
            throw new UnsupportedOperationException();
        }
        void setFoo(T foo) { 
            throw new UnsupportedOperationException();
        }
        public Iterator<Integer> iterator() {
            throw new UnsupportedOperationException();
        }

    }

顺便说一句,如果我将第一种情况更改为

    public class A<Integer> implements Iterable<Integer> {

我收到“隐藏”警告,即Integer (我认为在左侧)正在隐藏其他类型Integer

其实那是不对的! 更改为

    public class A<String> implements Iterable<Integer> {

String是隐藏String ,而不是隐藏Integer 我什至不知道那是什么意思。 Iterable<Integer>允许A<String> ,而A<T>不允许-这是我的问题的症结所在。


编辑:

我发现我的例子有问题。 对于示例,我从我们自己的接口LinkableVertex<OurLinkClass>更改为Iterable<Integer> LinkableVertex<OurLinkClass> ,并认为这没有什么不同。 OurLinkClass已实现OurLinkClass LinkableEdge<A> Eclipse中的实际错误是:

 Bound mismatch: The type OurLinkClass is not a valid substitute for the bounded parameter <E extends LinkableEdge<? extends LinkableVertex<E>>> of the type LinkableVertex<E> 

(在相关的情况下,这是一对递归接口: LinkableVertex<E extends LinkableEdge<? extends LinkableVertex<E>>>LinkableEdge<V extends LinkableVertex<? extends LinkableEdge<V>>> ))

就是说,尽管我还没有弄清所有内容,而且我不确定为什么需要额外的类型而不是原始类型的警告,但问题可能很简单,就像更改OurLinkClass来实现OurLinkClass LinkableVertex<A<?>>一样简单LinkableVertex<A<?>>

对于那个很抱歉!

隐藏意味着用于泛型的名称可能正在隐藏一个类: java.lang.String

将泛型用于类定义与将其用于变量(本地,参数,字段等)定义之间存在巨大差异。

定义不同:

public class A<String> {
             //^----^----- name of your generic used in the class
    public String getFoo() {
    }
}

比声明此:

A<String> a; //here A will work with generics but using java.lang.String class

同样,您的类可以实现使用泛型的接口,但这并不意味着您的类也必须使用泛型。 这是一个例子:

class MyClass<T> implements Iterable<T> {
    //this means MyClass will use a generic of name T and implements Iterable
    //to support the same generic T used in the class
}

class AnotherClass implements Iterable<String> {
    //this means that AnotherClass doesn't support generics
    //and implements Iterable for java.lang.String only.
}

暂无
暂无

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

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