java - 将通用类型 <T> 的元素添加到 LinkedList 的 arrayList

标签 java list hashtable indexoutofboundsexception

我想在 java 中创建一个哈希表类,我将键值对存储在链表的 ArrayList 中。我通过声明

 ArrayList<LinkedList<T>> storage = new ArrayList();

然后我想创建一个 linkList 对象,我可以使用它在 arrayList 的每个索引内创建一个新的链表。我通过声明来做到这一点:

  LinkedList<T> list = new LinkedList<T>();

然后我将我的添加函数设置为将元素添加到 LinkedList 的第一个索引,该索引位于 arrayList 的散列键索引内:

public void add(K key, T value){    
int arrayListIndex = (key.hashCode()) % this.initialCapacity;
    System.out.println(arrayListIndex); //This tells us where we access the Array List;


    if (hashBrown.get(arrayListIndex) == null){

        hashBrown.add(arrayListIndex, list);
        hashBrown.get(arrayListIndex).addFirst(value);
    }
}

每次运行此代码时,我都会收到一个错误,其中索引为 7,大小为 0。这会导致错误:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 7, Size: 0
    at java.util.ArrayList.rangeCheck(ArrayList.java:571)
    at java.util.ArrayList.get(ArrayList.java:349)
    at FastHashtable.add(FastHashtable.java:72)
    at FastHashtable.main(FastHashtable.java:145)

我无法追踪这个索引越界错误的来源,任何人都可以提供建议。我对使用 ArrayLists 还很陌生,这让我觉得我最初对 arrayList 的声明是不正确的。

最佳答案

你混淆了 ArrayList s 容量及其大小。来自 Oracle Java 文档:

Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.

相反,您应该考虑创建一个普通数组(例如 Object[] a = new Object[maxSize] ),您可以在其中实际分配任意索引值的对象(在本例中为链表)。如果只想存储链表,创建一个 LinkedList<T>[]数组。

关于java - 将通用类型 <T> 的元素添加到 LinkedList 的 arrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13326799/

相关文章:

java - tomcat 7.0 和 jax-ws 2.2.5 内存泄漏

java - 在java中排序 double

python - 不重复python的排列

java - HashTable 中的搜索功能

hashtable - Stata 简单键值对

java - JNA:关键监听器+JFrame

java - 将 CSS 资源添加到 Wicket Web 应用程序

java - 根据属性值从单个对象列表重建列表

javascript - 如何使用 jQuery 包装 x 个嵌套项目?

c++ - 从数组中查找重复的 3D 顶点