简体   繁体   English

在泛型类中实例化泛型类

[英]Instantiating a generic class in a generic class

I have the following first generic class and its interface:我有以下第一个泛型类及其接口:

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

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

And the second generic class and its 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();
    }

Suppose we're working on a method inside the second class, and we try to instantiate a new instance of the second class, and name it "result", then try to access its Generic2 instance, it will give an error:假设我们正在处理第二个类中的一个方法,我们尝试实例化第二个类的一个新实例,并将其命名为“result”,然后尝试访问它的 Generic2 实例,它会给出一个错误:

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

result.list will give an error: "list cannot be resolved or is not a field". result.list 将给出错误:“列表无法解析或不是字段”。 I think there must be a workaround to instantiate a generic class in a generic class.我认为必须有一种解决方法来实例化泛型类中的泛型类。 Thanks.谢谢。

EDIT: I need to conform to the interfaces in each implemented class.编辑:我需要符合每个实现类中的接口。 So as you can see the method union has to return object of type Generic2Interface that's why I declare result like this.因此,正如您所看到的,union 方法必须返回 Generic2Interface 类型的对象,这就是我像这样声明结果的原因。

You need a cast for result to Generic2 type.您需要将结果转换为Generic2类型。 This works:这有效:

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

Or this:或这个:

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

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

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