[英]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.