Java泛型,具有两个类之间的类型化容器/包含关系

时间:2011-03-09 13:59:24

标签: java generics data-structures

我希望产生一些基类,其中包括以下内容

class Container<T extends Containee>
{
     T containee;
     public T getContents(){return containee;}
     public void setContents(T contents){ containee = contents; containee.setContainer(this); }
}

class Containee<T extends Container>
{
     T container;
     public T getContainer(){return container;}
     public void setContainer(T container){this.container = container;}
}

这里有一个循环定义问题,我认为我可以轻松使用通配符

class Container<T extends Containee<?>>
class Containee<T extends Container<?>>

除了编译器抱怨containee.setContainer(this)。我已经破解了一些特殊的解决方案,这些解决方案将使超类能够编译,但是没有什么能用于子类,例如。

class Foo extends Container<Bar>
class Bar extends Containee<Foo> 

泛型教程和常见问题解答似乎与此无关。如何使用泛型来表达这种关系?

由于

4 个答案:

答案 0 :(得分:2)

也许是这样的:

abstract class Container<
    THIS extends Container<THIS, T>,
    T extends Containee<T, THIS>
> {
    T containee;

    protected abstract THIS getThis();

    public T getContents() {
        return containee;
    }
    public void setContents(T contents){
        containee = contents;
        containee.setContainer(getThis());
    }
}

class Containee<
    THIS extends Containee<THIS, T>,
    T extends Container<T, THIS>
> {
    T container;
    public T getContainer() {
        return container;
    }
    public void setContainer(T container) {
        this.container = container;
    }
}

(或者也许那些具有较少泛型的东西。)

答案 1 :(得分:2)

试试这个:

class Container<T extends Containee<Container<T>>>
{
   T containee;
   public T getContents(){return containee;}
   public void setContents(T contents){ containee = contents; containee.setContainer(this); }
}

class Containee<T extends Container<? extends Containee<T>>>
{
   T container;
   public T getContainer(){return container;}
   public void setContainer(T container){this.container = container;}
}

class Bar extends Containee<Container<Bar>> {  
}

class Foo extends Container<Bar> {
}

Foo现在是一个接受Bar对象的容器,而Bar可以添加到扩展Container的任何容器中,所以这也是可能的:

class Baz extends Container<Bar> {
}

Baz也是Bar对象的容器。

答案 2 :(得分:1)

普通的旧多态性会更好吗?

class Container
{
    Containee containee;
    public Containee getContents(){return containee;}
    public void setContents(Containee contents){ containee = contents; containee.setContainer(this); }
}

class Containee
{
    Container container;
    public Container getContainer(){return container;}
    public void setContainer(Container container){this.container = container;}
}

答案 3 :(得分:0)

您的第一个解决方案有什么问题?

class Container<T extends Containee>
class Containee<T extends Container>