HashMap.get(linkedList)的结果抛出ClassCastException



在此基础上,我创建了这段代码,用于从LinkedList的HashMap中删除一个条目。

    //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

当这个函数的一部分在main中被调用时,我得到以下错误:

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)

这是我如何实现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     }

我的删除算法有什么问题?我理解它试图用一个不正确的参数使用compareTo,这就是抛出异常的原因,但我不应该从HashMap.get(listWanted)的结果调用LinkedList<Item>的任何函数吗?为什么Comparable是这里的一个因素?有人可以建议一个修复和纠正我的理解这一点吗?

编辑

第118行只是调用删除算法在

中的remove函数
118         removeBook(out, "The Curious Incident of the Dog in the Night-Time");

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     }

在287行中,您正在调用bookaisles .remove(book),它有效地尝试从包含String作为键的Treemap中删除Item
(Javadoc of Treemap: "如果指定的键不能与当前映射中的键进行比较,则抛出java.lang.ClassCastException ")

如果你将行改为bookAisle.remove(title),那么它应该可以工作

相关内容

  • 没有找到相关文章

最新更新