2016-05-22 108 views
1

构造的ArrayList:插入到链表

array = new ArrayList<LinkedList<String>>(size); 

试图与该线插入:

array[index].add(value); 

它返回一个错误“的类型的表达式必须是一个数组类型,但它解决ArrayList < \ LinkedList < \字符串>>“

我试图插入一个字符串到链接列表节点的数组索引使用添加linkedli st方法。为什么没有这条线路工作?

*这是一个HashMap实现顺便说一句,链表数组

回答

1

您不能访问这样的列表。

这里是你如何能做到这一点:

ArrayList<LinkedList<String>> array = new ArrayList<LinkedList<String>>(size); 

// add a bunch of lists 
// How many depends on how deep you want the chaining if you are doing  
// this for a hash function. 

array.add(new LinkedList<String>()); 
array.add(new LinkedList<String>()); 
array.add(new LinkedList<String>()); 
array.add(new LinkedList<String>()); 
array.add(new LinkedList<String>()); 

// Now based on what index you need (e.g. your hash result), you insert into that list. 
int index = hashFunction(...); 
array.get(index).add("abc"); 
+0

如果我想再次插入,它散列到另一个指标,就不是我要使用另一个变量名,一个LinkedList在索引中插入?如果我这样做,那么我不能有LinkedList list = new LinkedList ();在插入方法中,因为它继续使用变量名“list” –

+0

不,您只需获取需要插入的列表的索引,然后添加到该列表中。我假设你正试图做链接的哈希函数?我可以添加到我的答案,以显示多个列表。 –

+0

噢,我明白了,谢谢 –

0

阵列,可以使用[]操作。其他类型(如List S)也不能,并且必须使用方法(如get)来访问他们的内容:

array.get(index).add(value);