簡體   English   中英

java.lang.Boolean不能轉換為java.util.LinkedList

[英]java.lang.Boolean cannot be cast to java.util.LinkedList

我有一個HashMap ,其中鍵的類型為String ,值的類型為LinkedList ,類型為String

基本上,這就是我要做的事情。

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));
    }
}

我第一次添加一個鍵,值對,我沒有收到任何錯誤。 但是,當我嘗試檢索與現有密鑰關聯的鏈接列表時,我得到以下異常:

java.lang.Boolean cannot be cast to java.util.LinkedList. 

我沒有可能的解釋為什么會發生此異常。

試試這個:

while (contentItr.hasNext()) {
    String word = (String) contentItr.next();
    if (wordIndex.containsKey(word)) {
        LinkedList temp = (LinkedList) w.get(word);
        temp.addLast(currentUrl);
    } else {
        LinkedList temp = new LinkedList();
        temp.add(currentUrl);
        w.put(word, temp);
    }
}

正如您所看到的,問題在於向Map添加新元素的行 - 方法add返回一個布爾值,這就是添加到Map的內容。 上面的代碼修復了問題,並將您想要的內容添加到Map中 - 一個LinkedList。

另外,請考慮在代碼中使用泛型類型,這樣可以防止這樣的錯誤。 我會嘗試從你的代碼中猜出類型(必要時調整它們,你會得到這個想法),假設你在程序中的某個地方有這些聲明:

Map<String, String> wordIndex = new HashMap<String, String>();
Map<String, LinkedList<String>> w = new HashMap<String, LinkedList<String>>();

List<String> content = new ArrayList<String>();
Iterator<String> contentItr = content.iterator();

這樣,您的問題中的代碼片段就可以安全地編寫,避免不必要的強制轉換和類型錯誤,就像您擁有的那樣:

while (contentItr.hasNext()) {
    String word = contentItr.next();
    if (wordIndex.containsKey(word)) {
        LinkedList<String> temp = w.get(word);
        temp.addLast(currentUrl);
    } else {
        LinkedList<String> temp = new LinkedList<String>();
        temp.add(currentUrl);
        w.put(word, temp);
    }
}

編輯

根據下面的注釋 - 假設您實際上可以ArrayList替換LinkedList (對於某些操作可能更快),並且您使用的唯一 LinkedList特定方法是addLast (這是add的同義詞),上面的代碼可以按照以下方式重寫,使用接口而不是容器的具體類,更加面向對象:

Map<String, String> wordIndex = new HashMap<String, String>();
Map<String, List<String>> w = new HashMap<String, List<String>>();

List<String> content = new ArrayList<String>();
Iterator<String> contentItr = content.iterator();

while (contentItr.hasNext()) {
    String word = contentItr.next();
    if (wordIndex.containsKey(word)) {
        List<String> temp = w.get(word);
        temp.add(currentUrl);
    } else {
        List<String> temp = new ArrayList<String>();
        temp.add(currentUrl);
        w.put(word, temp);
    }
}

List.add返回boolean ,它被自動裝箱為Boolean 你的else子句正在創建一個LinkedList,調用一個返回boolean的方法( add ),並將生成的autoboxed布爾值放入map中。

你知道泛型嗎? 您應該鍵入w作為Map<String,List<String>>而不僅僅是Map。 如果您這樣做,則會在編譯時捕獲此錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM