【问题标题】:Java Generics: nested data structureJava 泛型:嵌套数据结构
【发布时间】:2015-12-12 23:41:58
【问题描述】:

我正在实现一个基于简单双向列表的 Java 泛型嵌套数据结构。

MyList 包含包含 Info 的 Node。

public class MyList<E> {
    public Node<E> head;
    public Node<E> tail;

    public MyList() {
        this.head = this.tail = null;
    }

    public add(E Info) {
        this.head = new Node<E>(info); // i'm considering just one element
    }
}

public class Node<E> {
    private Node<E> succ;
    private Node<E> pred;
    private E info;

    public Node(E info) {
        this.succ = this.pred = null;
        this.info = info
    }
}

public class Info<K,V> {
    public K key;
    public V value;

    public Info(K key, V value) {
        this.key = key;
        this.value = value;
    }
}

现在我想实现以下目标。

  1. 创建一个 MyList 对象数组。
  2. 每个列表的每个节点都应该包含一个 Info 对象; 3 .Info 对象应该包含一对 Key (Integer) / Value (MyList object);
  3. 列表的每个节点都应包含 Info 对象;
  4. 每个 Info 对象都应该包含一对 Key (Integer) / Value (String);

第一个问题:我知道 Java 不允许创建泛型数组;是否有解决方法来创建它?

好的,让我们尝试一个“平面”对象。

MyList<Info> myList = new MyList<Info>();

现在我创建一个新的 Info 对象,add 方法将放置在 Node 中。

myList.add(new Info<Integer,MyList<E>>(new Integer(10), new MyList<Info>()));

但是想走得更远……

myList.head.value.insert(new Info<Integer,myList<Info>>(new Integer(10), new myList<Info>()));

...抛出以下错误:

cannot find symbol,
symbol: method insert(Info<Integer,MyList<Info>>)
location: class Object

第二个问题:Object 类呢?我应该有一个 List 对象!

第三个问题:这是管理泛型的正确方法吗?

提前感谢您的帮助。

【问题讨论】:

    标签: java generics data-structures nested


    【解决方案1】:
    1. 您不能实例化泛型数组,但始终可以使用ArrayList。您可以以可忽略的开销安全地获得相同的功能。

    2. 在创建列表时,您没有指定 Info 的类型参数

      MyList<Info> myList = new MyList<Info>();
      

      相反,它应该是

      MyList<Info> myList = new MyList<Info<Integer, MyList<Info<Integer, String>>>>();
      

      由于您没有指定类型参数,Java 编译器将它们默认为 Object 类(导致上述错误)。

    3. 错误是由于不正确地处理泛型造成的。上述修复应该可以解决该错误。一般来说,避免使用原始类型(始终提供适当的类型参数)。

    希望这会有所帮助。
    祝你好运。

    【讨论】:

    • 根据您的回复,我找到了初始化泛型嵌套对象的正确方法:MyList&lt;Info&lt;Integer, MyList&lt;Info&lt;Integer, String&gt;&gt;&gt;&gt; myList = new MyList&lt;Info&lt;Integer, MyList&lt;Info&lt;Integer, String&gt;&gt;&gt;&gt;(); 和myList.add(new Info&lt;Integer, MyList&lt;Info&lt;Integer, String&gt;&gt;&gt;(new Integer(10), new MyList&lt;Info&lt;Integer, String&gt;&gt;())); 最后看起来很困惑,也许我应该找到一个更简单的方法。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-14
    • 2012-06-03
    • 1970-01-01
    相关资源
    最近更新 更多