java - 在泛型类中实例化泛型类

标签 java generics instance

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

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

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

第二个泛型类及其接口(interface):

    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 将给出错误:“列表无法解析或不是字段”。我认为必须有一个解决方法来实例化泛型类中的泛型类。 谢谢。

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

最佳答案

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

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

或者这个:

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

关于java - 在泛型类中实例化泛型类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46789126/

相关文章:

c# - 尽管 list<T> 在内部使用数组(固定的),但它如何动态工作?

java - 通过名称创建内部静态类实例

java - 我们可以在早期版本的 tableau 中使用 java 读取 tableau 摘录吗?

java - 企业 Java Webstart 分发 : use site-wide accepted certificate to sign a code-signing certificate

c#-4.0 - 如何获取重载静态方法的 MethodInfo?

java - 为特定类型的类声明一个字符串到类的映射

postgresql - Haskell PostgreSQL 简单 FromField

haskell - 为什么在 Haskell 中声明参数化数据类型?

java - SQLiteDatabase 的 int ""无效

java - 如何替换字符串中的单词?