Jakkie Chan
Jakkie Chan

Reputation: 317

Inserting to an ArrayList of LinkedList

Constructor:

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

Trying to insert with this line:

array[index].add(value);

It return an error saying "The type of the expression must be an array type but it resolved to ArrayList<\LinkedList<\String>>"

I'm trying to insert a string into a linkedlist node in an array index using the add linkedlist method. Why isn't that line working?

*This is a hashmap implementation btw, an array of linked lists

Upvotes: 1

Views: 3780

Answers (2)

Michael Markidis
Michael Markidis

Reputation: 4191

You can't access a list like that.

Here's how you can do this:

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");

Upvotes: 1

Mureinik
Mureinik

Reputation: 311228

Arrays use the [] operator. Other types (such as Lists) can't, and must use methods (such as get) to access their elements:

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

Upvotes: 0

Related Questions