1

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

2 Answers 2

1

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");
Sign up to request clarification or add additional context in comments.

2 Comments

If I wanted to insert again, and it hashes to another index, wouldn't I have to use another variable name for a linkedList to insert in that index? If I do, then I couldnt have LinkedList list = new LinkedList<String>(); in the insert method since it keeps using the variable name "list"
No, you would just get the index of the list you need to insert into, then add to that list. I assume you are trying to do a hash function with chaining? I can add to my answer to show it with multiple lists.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.