java – Generic Restriction Hell:Bound Mismatch
|
我正在开发一个具有广泛的泛型继承和依赖树的项目.转到编辑以查看更好的示例.基础知识看起来像这样: class A {
...
}
class B {
...
}
class C extends B {
...
}
class D<T extends B> extends A {
...
}
class StringMap<T extends A> {
HashMap<String,T> _elements;
...
}
所以现在我要编写一个包含特定StringMap类型的类. class X {
StringMap<D<C>> _thing = new StringMap<D<C>>;
...
}
到目前为止这一切都很好. d< c取代;实际上是一个非常长的名称,并且特定组合将在代码的其他部分中非常频繁地出现,因此我决定使用特定组合的类,以便更清楚并且具有更短的名称. class DC extends D<C> {
}
//and go to update X
class X {
StringMap<D<C>> _thing = new StringMap<D<C>>(); //still works fine
StringMap<DC> _thing = new StringMap<DC>(); //error
...
}
Eclipse给出了错误
所以问题是,为什么这不仅仅起作用? DC不做任何事情,只是延伸D< C>.并回应构造函数.为什么StringMap看到DC是不同的,因为它只是一个它除外的子类? 编辑: public abstract class Undoable<T> implements Comparable<T> {
public abstract T clone();
public abstract void updateFields(T modified);
}
abstract public class A<T extends A<T,U>,U extends Comparable<U>>
extends Undoable<T> {
abstract U getKey();
@Override
public int compareTo(T element)
{
return getKey().compareTo(element.getKey());
}
}
public class B<T extends B<T>> extends A<T,String> {
@Override
public T clone()
{
// TODO Auto-generated method stub
return null;
}
@Override
public void updateFields(T modified)
{
// TODO Auto-generated method stub
}
@Override
String getKey()
{
// TODO Auto-generated method stub
return null;
}
}
public class C extends B<C> {
}
public class D<T extends B<T>> extends A<D<T>,String> {
@Override
String getKey()
{
// TODO Auto-generated method stub
return null;
}
@Override
public D<T> clone()
{
// TODO Auto-generated method stub
return null;
}
@Override
public void updateFields(D<T> modified)
{
// TODO Auto-generated method stub
}
}
public class DC extends D<C> {
}
public class StringMap<T extends Undoable<T>> {
HashMap<String,T> _elements;
}
public class Main {
public static void main(String[] args)
{
StringMap<D<C>> _thing = new StringMap<D<C>>(); //works
StringMap<DC> _thing1 = new StringMap<DC>(); //error
//Bound mismatch: The type DC is not a valid substitute for
//the bounded parameter <T extends Undoable<T>> of the type StringMap<T>
}
}
解决方法你必须做错其他的事情,因为以下工作正常:import java.util.HashMap;
public class Q {
class A {
}
class B {
}
class C extends B {
}
class D<T extends B> extends A {
}
class StringMap<T extends A> {
HashMap<String,T> _elements;
}
class DC extends D<C> {
}
//and go to update X
class X {
StringMap<D<C>> thing1 = new StringMap<D<C>>(); // still works fine
StringMap<DC> thing2 = new StringMap<DC>(); // NO error!!!
}
}
试着发布这样一个类来重现你的错误. (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
