【发布时间】:2016-11-15 03:13:21
【问题描述】:
处理this 和类似条目,我创建了这段代码来从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 }
【问题讨论】:
-
请向我们展示 Assignment3.java 中的第 118 行。
-
您的
book变量是String类型而不是Item类型? -
堆栈跟踪显示的是 TreeMap,而不是 HashMap。您的代码没有显示。
-
@SeanPatrickFloyd 这个函数中唯一的 TreeMap 是 bookAisle,我在第 287 行调用了一个 Item 类型的参数,而它本应使用 String 类型的参数(即键)调用。感谢您指出我的愚蠢错误!
标签: java linked-list hashmap comparable