Reputation: 329
Working off this and similar entries I created this piece of code to remove an entry from a HashMap of LinkedList.
//Dbase in question
HashMap<String, LinkedList<Item>> authorDbase = new HashMap<String, LinkedList<Item>>();
TreeMap<String, Item> bookAisle = new TreeMap<String, Item>();
...
Item book = bookAisle.get(title); // book == title's Item object reference
authorDbase.get(author).remove(book); //Removes the item mapped to specified keyword
When the function this is a part of is called in main I get the following error.
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to library.Item
at library.Item.compareTo(Item.java:8)
at java.util.TreeMap.getEntry(TreeMap.java:352)
at java.util.TreeMap.remove(TreeMap.java:603)
at library.Library.removeBook(Library.java:287)
at Assignment3.removeBook(Assignment3.java:134)
at Assignment3.main(Assignment3.java:118)
Here is how I implemented Comparable<Item>
8 public abstract class Item implements Comparable<Item>
9 {
...
26 @Override
27 public int compareTo(Item i)
28 {
29 // String title = this.title; DEBUG FLAG: delete maybe?
30 return this.title.compareTo(i.title); //Returns a negative value if title < i.title, implements alphabetical order by title
31 }
What's wrong with my deleting algorithm? I understand that it's trying to use compareTo
with an incorrect argument and that's what is throwing the exception but shouldn't I be able to call any function of LinkedList<Item>
from the result of a HashMap.get(listWanted)
? Why is Comparable
a factor here? Could someone please suggest a fix and correct my understanding of this?
EDIT
Line 118 just calls the remove function that the deleting algorithm is in
118 removeBook(out, "The Curious Incident of the Dog in the Night-Time");
Here is removeBook
279 public boolean removeBook(String title)
280 {
281 Item book = bookAisle.get(title); // book == title's Item object reference
282 String author;
283 boolean successFlag = false;
284
285 if(book == null) //title doesn't exist in the bookAisle
286 successFlag = false;
287 else if (bookAisle.remove(book) != null) //It does exist and was removed
288 {
289 //Deletes from author dbase
290 author = book.getCreator(); //placed here to avoid potentially calling on a null object
291 authorDbase.get(author).remove(book); //Removes the item mapped to specified keyword
292 //Deletes from keyword dbase
293 removeFromKDbase(book); //Removes object reference from KDbase
294 successFlag = true;
295 }
296
297 return successFlag;
298 }
Upvotes: 0
Views: 597
Reputation: 794
In line 287 you are calling bookAisle.remove(book), which effectively tries to remove an Item
from a Treemap that does contain String
as key.
(Javadoc of Treemap: "throws java.lang.ClassCastException if the specified key cannot be compared with the keys currently in the map".)
If you change the line to bookAisle.remove(title)
, then it should work.
Upvotes: 2