gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 06:27:42 25 4
gpt4 key购买 nike

我有以下第一个泛型类及其接口(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com