由于HashMap.get(linkedList)而抛出ClassCastException

时间:2016-11-15 03:13:21

标签: java linked-list hashmap comparable

关闭this和类似的条目,我创建了这段代码,从LinkedList的HashMap中删除一个条目。

public void addGeofencesButtonHandler(View view) {
    if (!mGoogleApiClient.isConnected()) {
        Toast.makeText(this, getString(R.string.not_connected), Toast.LENGTH_SHORT).show();
        return;
    }

    try {
        populateGeofenceList();// creates geofence from list 
        LocationServices.GeofencingApi.addGeofences(
                mGoogleApiClient,
                // The GeofenceRequest object.
                getGeofencingRequest(),
                // A pending intent that that is reused when calling removeGeofences(). This
                // pending intent is used to generate an intent when a matched geofence
                // transition is observed.
                getGeofencePendingIntent()
        ).setResultCallback(this); // Result processed in onResult().
    } catch (SecurityException securityException) {
        // Catch exception generated if the app does not use ACCESS_FINE_LOCATION permission.
        logSecurityException(securityException);
    }
}

当在main中调用此函数时,我得到以下错误。

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

以下是我实施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的任何函数从LinkedList<Item>的结果?为什么HashMap.get(listWanted)是一个因素?有人可以建议修正并纠正我对此的理解吗?

修改

第118行只调用删除算法所在的删除功能

Comparable

以下是118 removeBook(out, "The Curious Incident of the Dog in the Night-Time");

removeBook

1 个答案:

答案 0 :(得分:2)

在第287行中,您正在调用bookAisle.remove(book),它有效地尝试从包含Item的树图中删除String作为键。
(Treemap的Javadoc: “如果无法将指定的键与当前地图中的键进行比较,则抛出java.lang.ClassCastException。”

如果您将行更改为bookAisle.remove(title),那么它应该可以正常工作。