繁体   English   中英

java中有两个键的数据结构

[英]Data structure having two keys in java

我有以下场景。

1) 模块 A 向模型 B 发送参数,然后模块 B 向模块 C 发出请求以提供该参数的值。 (可以有许多请求者,即模块 A1、A2 等作为模块 A)。 然后模块 C 将参数值发送到模块 B,然后模块 B 将值发送回模块 A。因此,模块 B 是一个中间件。

2)在此模块B给出了一个独特intKey各请求者(到模块A1,A2等)和模块C给出了每个请求者独特StringKey到模块B.

3) 模块 B 负责为正确的请求者提供正确的值。 这意味着它必须将 StringKey 映射到 intKey。 目前它通过创建两个并发哈希图来实现。 i) intKey,StringKey和 ii) StringKey,intKey

现在的问题是模块 B 必须一直遍历 Map 以找到正确的请求者(模块 A)。

我想知道我是否可以拥有一个数据结构,其中我有两个键,如果我给任何人说 Key1,那么我可以检索其相应的 key2 以及其他方式。 有什么办法可以摆脱这两个并发的 Hashmap 吗? 我将非常感谢任何有关这方面的帮助。

基本上不 - 您不能避免使用两个地图,并发或其他方式,因为您正在使用两种不同类型的密钥(除非您决定使用Map<Object,Object>这将是犯罪行为)。

但是 - 您可以隐藏复杂性:

public interface BiMap<P, Q> {

    public Q putQ(P key, Q value);

    public Q getQ(P key);

    public P putP(P key, Q value);

    public P getP(Q key);
}

现在将您的两张地图包裹在其中一张中,事情看起来更整洁,只是里面不整洁。

这应该有效:

public class BiMap<P, Q> {

    final Map<P, Q> pq;
    final Map<Q, P> qp;

    public BiMap(MapFactory maker) {
        pq = maker.<P, Q>make();
        qp = maker.<Q, P>make();
    }

    public BiMap() {
        // Default to ConcurrentHashMap
        this(MapFactory.ConcurrentHashMap);
    }

    public Q putQ(P key, Q value) {
        return pq.put(key, value);
    }

    public Q getQ(P key) {
        return pq.get(key);
    }

    public P putP(Q key, P value) {
        return qp.put(key, value);
    }

    public P getP(Q key) {
        return qp.get(key);
    }

    // Puts both at once.
    public synchronized void put(P p, Q q) {
        putQ(p, q);
        putP(q, p);
    }

    public enum MapFactory {

        ConcurrentHashMap {

                    @Override
                    <P, Q> Map<P, Q> make() {
                        return new java.util.concurrent.ConcurrentHashMap<P,Q>();
                    }

                };

        abstract <P, Q> Map<P, Q> make();
    }
}

暂无
暂无

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

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