繁体   English   中英

在泛型类中实例化泛型类

[英]Instantiating a generic class in a generic class

我有以下第一个泛型类及其接口:

    public interface Generic1Interface<E extends Comparable> {
    ..
    }

    public class Generic1 <E extends Comparable> implements 
    Generic1Interface<E>  {
    .. //implementation of Doubly linked list using Node objects
    }

第二个泛型类及其接口:

    public interface Generic2Interface<E extends Comparable> {
    ..
    }

    public class Generic2 <E extends Comparable> implements 
    Generic22Interface<E>  {
      Generic1Interface<E> list;
        //so nothing here but a reference to an object of type Generic1Interface<E>
    Generic2() {
      list = new Generic1();
    }

假设我们正在处理第二个类中的一个方法,我们尝试实例化第二个类的一个新实例,并将其命名为“result”,然后尝试访问它的 Generic2 实例,它会给出一个错误:

    public Generic2Interface<E> union (E a, E b) {
      Generic2Interface<E> result = new Generic2();
      **result.list** = ....;

result.list 将给出错误:“列表无法解析或不是字段”。 我认为必须有一种解决方法来实例化泛型类中的泛型类。 谢谢。

编辑:我需要符合每个实现类中的接口。 因此,正如您所看到的,union 方法必须返回 Generic2Interface 类型的对象,这就是我像这样声明结果的原因。

您需要将结果转换为Generic2类型。 这有效:

System.out.println(((Generic2)result).list);

或这个:

Generic2<E> result = new Generic2();
System.err.println(result.list);

暂无
暂无

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

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