简体   繁体   English

HashMap.containsKey() - 如何搜索 class?

[英]HashMap.containsKey() - how to search for a class?

Hello你好
if you search in an HashMap<String,String> for a specific value of a key-value-pair, you can write the following:如果您在HashMap<String,String>中搜索键值对的特定值,则可以编写以下内容:

myHashMap.containsKey(myString);

But how can I manage it if the key is not a string?但是,如果密钥不是字符串,我该如何管理它? I have a class which looks like this:我有一个 class 看起来像这样:

public class Kategorie implements Comparable {
    private String name;

    public Kategorie()  {
        super();
    }

    public Kategorie(String name)  {
        setName(name);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public int compareTo(Object o) {
        if (!(o instanceof Kategorie))  
           throw new ClassCastException();

        Kategorie k = (Kategorie)o;
        String name = k.getName();
        return this.getName().compareTo(name);

    }
}

In a map I saved keys and values of this type "Kategorie".在 map 中,我保存了这种“类别”类型的键和值。

mapKategorieDEundEN.put(new Kategorie(strName_de), new Kategorie(strName_en));

Later in the code, I want to check if there is a key with a specific string.稍后在代码中,我想检查是否有带有特定字符串的键。

if (mapKategorieDEundEN.containsKey(searchString))  {

...doesn't work, because the key is not a string but a "Kategorie", that's clear. ...不起作用,因为密钥不是字符串而是“类别”,这很清楚。

Then I tried something like this:然后我尝试了这样的事情:

if (mapKategorieDEundEN.containsKey(new Kategorie(searchString)))  {

...doesn't work too. ……也不行。 I assume that it doesn't find anything because the object is not the "original" object but a new one.我认为它没有找到任何东西,因为 object 不是“原始” object 而是一个新的。

In this case, can I use containsKey at all or do I have to use a loop over the HashMap?在这种情况下,我可以完全使用 containsKey 还是必须在 HashMap 上使用循环?

You class should override equals and hashCode , it will work after that.您 class 应该覆盖equalshashCode ,之后它将起作用。

The HashMap/Hashtable puts the items in "buckets" by using the hashCode of the key, so a new object that represents the same value as another object, and which should be considered as the same object must return the same hashCode. HashMap/Hashtable 使用键的 hashCode 将项目放入“桶”中,因此一个新的 object 表示与另一个 object 相同的值,并且应该被视为相同的 ZA8CFDE6331BD59EB2AC96F8911C466 必须返回相同的 hashCode。 All keys that return the same hashCode will then be considered as candidates, and equals will be invoked on them.所有返回相同 hashCode 的键都将被视为候选键,并且将对它们调用 equals。 It's considered a match if equals returns true.如果 equals 返回 true,则认为匹配。

HashMap uses hashCode() and equals() . HashMap 使用hashCode()equals() You have to implement them.你必须实施它们。 If you don't know how.如果你不知道怎么做。 Check your IDE (eclipse) usually can generate them for you.检查您的 IDE (eclipse) 通常可以为您生成它们。

If you want to access your objects using your compareTo method, you should not use a hashCode/equals based Map, but a SortedMap, like TreeMap (or ConcurrentSkipListMap).如果要使用compareTo方法访问对象,则不应使用基于 hashCode/equals 的 Map,而应使用 SortedMap,如 TreeMap(或 ConcurrentSkipListMap)。

This has the added benefit that it enables range-based queries (eg "give me all categories larger than this one"), but is a bit slower (O(log n) instead of O(1)) for simple get accesses compared to hash-based access (with a good hash code, not a constant one).这有一个额外的好处,它支持基于范围的查询(例如“给我所有大于这个的类别”),但与简单的get访问相比有点慢(O(log n)而不是 O(1))基于哈希的访问(具有良好的 hash 代码,而不是恒定代码)。

For a general use class, defining both hashCode/equals and compareTo would be sensible, then the user of the class can decide which type of map to use.对于一般用途 class,定义 hashCode/equals 和 compareTo 是明智的,然后 class 的用户可以决定使用哪种类型的 map。 (If there are different ways to sort your objects, better provide different Comparator objects.) (如果有不同的方法对对象进行排序,最好提供不同的 Comparator 对象。)

As a side remark, you should not implement Comparable , but Comparable<Kategorie> .附带说明一下,您不应该实现Comparable ,而应该实现Comparable<Kategorie> Then your compareTo method would look like this:然后您的compareTo方法将如下所示:

public int compareTo(Kategorie k) {
    String name = k.getName();
    return this.getName().compareTo(name);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 HashMap.containsKey()返回false。 为什么? - HashMap.containsKey() returns false. Why? HashMap.containsKey 由于某种原因不起作用 - HashMap.containsKey not working for some reason java中HashMap.containsKey()的时间复杂度是多少? - What is the time complexity of HashMap.containsKey() in java? HashMap.containsKey(key) 找不到键,自定义类用作键类型 - HashMap.containsKey(key) failing to find key, with custom class used as key type Java HashMap.containsKey()不调用equals() - Java HashMap.containsKey() doesn't call equals() Java-HashMap.containsKey返回对象的错误值 - Java - HashMap.containsKey returning incorrect values for Objects ArrayList.contains()vs HashMap.containsKey()vs HashMap.get() - ArrayList.contains() vs HashMap.containsKey() vs HashMap.get() 为什么使用Hashmap.containsKey比Arrays.binarySearch运行得快得多? - Why using Hashmap.containsKey run faster considerably than Arrays.binarySearch? 文件的第一个单词没有被 hashmap.containskey 识别为与文件中稍后出现的其他单词相同的单词 - First word of file isn't being recognized as same word as other occurences later in file by hashmap.containskey 为什么在部署的环境中,对Hashmap.containsKey()的调用比本地调用慢100倍? - Why would a call to Hashmap.containsKey() be 100 times slower in deployed environment vs local?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM