gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:02:53 24 4
gpt4 key购买 nike

我想在 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/

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