开发者

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).


Iterate over keyset or entryset.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜