【问题标题】:How do i find a value stored in a linked list than in turn is stored in a hashmap我如何找到存储在链表中的值而不是存储在哈希图中的值
【发布时间】:2014-11-26 12:44:01
【问题描述】:

我有以下哈希图,它存储字符串键和链表值

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

我的wordIndex包含多个包含“算法”这个词的链表,所以我写了下面的代码来看看我的hashmap是否能够找到“算法”这个词

String getWord(String query) { //query=user input in this case algorithms

    if(wordIndex.containsValue(query.toLowerCase()))
    {
        return "hello";          //should return hello if word is found
    }
    else
    {
        return "none";
    }       
}

但是它总是返回 none,这意味着它可以在链表中找到单词。 那么遍历Hashmaps中的链表的正确过程是什么。我搜索了但找不到任何答案。

我还需要返回所有包含查询词的 KEYS(在本例中为“算法”)。我似乎无法在 hashmap 类中找到可以做到这一点的函数(或者我可能看到但不理解)。我是 hashmaps 的新手,请你们帮助我并指出正确的方向。

【问题讨论】:

  • 您正在根据 LinkedList 对象检查字符串,该对象永远不会匹配。

标签: java linked-list hashmap


【解决方案1】:

你不能那样做。如果你想检查 HashMap 的任何 LinkedList 中是否有这个词,你应该这样做:

String getWord(String query) { //query=user input in this case algorithms
    for(LinkedList<String> l : wordIndex.values()) {
        if(l.contains(query.toLowerCase())) {
            return "hello";          //should return hello if word is found
        }
    }
    return "none";   
}

【讨论】:

  • 非常感谢,所以这个过程是使用增强的 for 循环(或迭代器,我猜也可以)。关于如何让钥匙归还的任何想法?
  • 您可以在 wordIndex.entrySet() 上使用 for 循环。 En Entry 是存储在映射中的 (Key, Value) 对。请参阅:docs.oracle.com/javase/7/docs/api/java/util/…
【解决方案2】:
public boolean containsValue(Object value) {
if (value == null)
        return containsNullValue();

Entry[] tab = table;
    for (int i = 0; i < tab.length ; i++)
        for (Entry e = tab[i] ; e != null ; e = e.next)
            if (value.equals(e.value))
                return true;
return false;
}

如果您查看 containsValue 方法,您将看到它使用 Entry 对象 equals 方法进行匹配,如果您查看此 Entry 类 equals 方法对象而不是 Entry 类型,则返回 false。我认为最好的方法是在为每条记录迭代地图时使用链表的包含方法

 public final boolean equals(Object o) {
        if (!(o instanceof Map.Entry))
            return false;
        Map.Entry e = (Map.Entry)o;
        Object k1 = getKey();
        Object k2 = e.getKey();
        if (k1 == k2 || (k1 != null && k1.equals(k2))) {
            Object v1 = getValue();
            Object v2 = e.getValue();
            if (v1 == v2 || (v1 != null && v1.equals(v2)))
                return true;
        }
        return false;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多