I have a HashMap where the key is of type String and the value is of type LinkedList of type String.
So basically, here’s what I’m trying to do.
while (contentItr.hasNext()) {
String word = (String) contentItr.next();
if (wordIndex.containsKey(word)) {
LinkedList temp = (LinkedList) w.get(word); //Error occurs here
temp.addLast(currentUrl);
} else {
w.put(word, new LinkedList().add(currentUrl));
}
}
The first time that I add a key,value pair, I receive no error. However, when I try to retrieve the linked list associated with an existing key, I get the following exception:
java.lang.Boolean cannot be cast to java.util.LinkedList.
I don’t have a possible explanation of why this exception occurs.
Try this instead:
The problem, as you can see, was in the line that adds a new element to the Map – the method
addreturns a boolean value, and that’s what was being added to the Map. The code above fixes the problem and adds what you intended to the Map – a LinkedList.As an aside note, consider using generic types in your code, in that way errors like this can be prevented. I’ll try to guess the types from your code (adjust them if necessary, you get the idea), let’s say you have these declarations somewhere in your program:
With that, the piece of code in your question can be safely written, avoiding unnecessary casts and type errors like the one you had:
EDIT
As per the comments below – assuming that you actually can replace the
LinkedListby anArrayList(which might be faster for some operations) and that the onlyLinkedList-specific method you’re using isaddLast(which is a synonym foradd), the above code can be rewritten as follows, in a more Object-Oriented style using interfaces instead of concrete classes for the containers: