简体   繁体   中英

How to get object from Map with different key?

I have a map that stores my ClassA as a key and some exception as a value.

I also have a list that contains ClassB objects.

ClassA has an entry X (Long) and ClassB has an entry Y(ClassY) and it has field X (String) too.

Now I should find in map where ClassA.getX == ClassB.getY.getX

But problem is I can search ın map only by key and key object must be ClassA. Otherwise it returns null.

Here is my iteration:

               list = listModelNewSc;
    for (int i = 0; i <  exceptionMap.size(); i++) {
        for (int k = 0; k < list.getSize(); k++) {
            if (((ClassA) exceptionMap.get(i)).getX() == Long
                    .parseLong((((CLassB) list.getElementAt(k)).getY().getX()))) {
                Listitem itemAtIndex = list.getItemAtIndex(i);

                if (itemAtIndex != null) {
                    System.out.print("FOUND");
                }

            }
        }
    }

The only way to do this with the setup you described is to iterate through all the keys in the map until you find the one you want.

Alternatively, you could have have a second map with ClassA.getX as the key (mapping to the same value).

Essentially it's a trade off, the first solution is slower but uses less memory, the second solution is faster but uses more memory (you have two copies of the map).

遍历键集或条目集。

A solution, haven't tried but tell me if it works :)
As far as I know when you call Map.get(...) it uses the keys' equals(o) and hashCode() methods. As a solution to your problem you could override these methods of ClassA in a kinda "wrong" way, like this:

@Override
public int hashCode() {
    // If you know that the code of a key instance has no logic value anywhere else, give constant value here and in ClassB
    return 99827;
}

@Override
public boolean equals(Object o) {
    // This will (maybe) make Map.get(ClassB) work with ClassA as a key
    if (o instanceof ClassB) {
        ClassB cb = (ClassB) o;
        return this.getX() == cb.getY().getX();
    } else if (o instanceof ClassA) {
        // ...
    }
    return false;
}

So then you'll just do exceptionMap.get(classB) and hopefully get the exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM