【问题标题】:Adding a number into a LinkedList, inside an ArrayList在 ArrayList 内将数字添加到 LinkedList
【发布时间】:2020-05-27 04:52:33
【问题描述】:

我正在尝试将整数添加到 LinkedList;但是,我不确定如何将整数添加到已经存在的 LinkedList。

class HashChaining extends HashTable {

private ArrayList<LinkedList<Integer>> chains;
private HashFunction function;

   HashChaining (Hashfunction function) {

      this.function = function;
      this.chains = new ArrayList<>(capacity);
        for (int i=0; i<capacity; i++)
            chains.add(i, new LinkedList<>());
   }

   void insert(int key) {
        int location = function.apply(key);
        chains.add(location, new LinkedList<Integer>(chains.get(location).push(key)));

   } 

【问题讨论】:

  • JDK LinkedList 没有 push 会返回列表。您不确定如何将元素添加到列表中是不正确的:您已经在构造函数中完成了一次。

标签: java list arraylist linked-list hashtable


【解决方案1】:

如果您查看javadoc,您会发现add​(int index, E element) 方法在给定索引处插入一个元素。您想要实现的是将元素添加到内部列表:

chains.get(location).add(key)

chains.get(location) 将在location 给定的位置上检索内部LinkedList,然后在此列表中添加您的元素。

【讨论】:

    猜你喜欢
    • 2015-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-09
    相关资源
    最近更新 更多