如何類似的功能沒有錯誤來實現的?強制Java的泛型參數是同類型
class A<K> {
void f(K x) {}
}
void foo(A<? extends X> a, X x) {
a.f(x); // AN error: The method f(capture#1-of ? extends X) in the
// type A<capture#1-of ? extends X> is not applicable for the
// arguments (X)
}
我知道,這是因爲「A」可以是A <「非X」>的一個實例,因此它的「F」不得接受X的實例作爲參數,但怎麼也我強制參數是相同的類型?
這裏是更多的代碼:
測試類:
class Test {
<T> void foo(A<T> a, T x) {
a.f(x); // now it works!
}
}
在某些類:
Container<X> container;
public void test() {
X x = new X();
new Test().foo(container.get(), x);
}
這裏的容器類:
public class Container<K> {
A<? extends K> get() {
return new A<K>();
}
}
X是類還是類型參數? – Joni