Java linkedlist的arraylist中未初始化的插槽 int index=hash(值、大小); if(array.get(index)==null){ add(index,newlinkedlist()); }

Java linkedlist的arraylist中未初始化的插槽 int index=hash(值、大小); if(array.get(index)==null){ add(index,newlinkedlist()); },java,arrays,list,arraylist,linked-list,Java,Arrays,List,Arraylist,Linked List,我有一个LinkedList数组:Arraylist,如果尚未初始化LinkedList,我想在给定的数组索引中添加一个LinkedList。问题是,索引散列到某个数字,但它所指向的索引不存在,因为该索引中尚未初始化任何LinkedList,但这就是为什么我要做if(array.get(index)==null)添加LinkedList,但显然这是一个不正确的比较 我尝试了.isEmpty(),null,和.equals(null),它们不起作用。数组列表不能自动增长,你必须自己增长: int

我有一个LinkedList数组:
Arraylist
,如果尚未初始化LinkedList,我想在给定的数组索引中添加一个LinkedList。问题是,索引散列到某个数字,但它所指向的索引不存在,因为该索引中尚未初始化任何LinkedList,但这就是为什么我要做
if(array.get(index)==null)
添加LinkedList,但显然这是一个不正确的比较


我尝试了
.isEmpty()
null
,和
.equals(null)
,它们不起作用。

数组列表不能自动增长,你必须自己增长:

int index = hash(value, size);

if (array.get(index) == null) {
    array.add(index, new LinkedList<String>());
}

正如Tamas Rev所说:您不必重新发明轮子,只需使用
HashMap
。作为额外的奖励,
HashMap
很可能更快,并且通常更高效(上面的方案分配了一个
limit
元素数组,而
HashMap
可以处理任何大小的键类型)。

需要明确的是,您有一个
ArrayList
,而不是一个数组。您是否用预定义的大小实例化了
ArrayList
?如果不是,则其大小为0,因此您不能首先按索引添加,因为它将抛出
数组索引OutofBoundsException
。我有个坏消息告诉您:重新实现
哈希映射。您可以直接使用它,它会很好。这看起来很奇怪,为什么要使用哈希函数来确定arraylist的索引?但是.add(index,new-llist)会抛出错误,因为索引超出边界,并且在arraylist中还不存在。get(index)或.add(index)会导致相同的问题。在这种情况下,为什么需要ArrayList?你应该使用一个LinkedListI数组,但我怀疑这可能是因为你建议OP将他的
ArrayList
扩展到数亿个条目,甚至数十亿个条目(取决于
hash()
),将其变成一个巨大的内存消耗。
int index = hash(value, size);

// grow
if (array.size() <= index) {
    array.ensureCapacity(index + 1);
    while (array.size() <= index)
        array.add(null);
}

if (array.get(index) == null) {
    array.set(index, new LinkedList<String>());
}
// initialise
ArrayList<LinkedList<String>> array = new ArrayList<>();
array.ensureCapacity(limit);
for (int i = 0; i < limit; ++i)
    array.add(null);

// ...

// use
int index = hash(value, size); // hash(...) returns values in 0..limit-1
if (array.get(index) == null) {
    array.set(index, new LinkedList<String>());
}