【问题标题】:Data structure having two keys in javajava中具有两个键的数据结构
【发布时间】:2014-08-06 15:52:40
【问题描述】:

我有以下场景。

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

2) 此处,模块 B 为每个请求者(模块 A1、A2 等)提供一个唯一的 intKey,模块 C 为模块 B 的每个请求者提供唯一的 StringKey .

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

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

我想知道我是否可以有一个数据结构,其中我有两个键,如果我给任何人说 Key1,那么我可以检索其对应的 key2 以及另一种方式。有什么办法可以摆脱这两个并发的 Hashmap 吗?对于这方面的任何帮助,我将不胜感激。

【问题讨论】:

    标签: java data-structures key concurrenthashmap


    【解决方案1】:

    基本上不 - 您无法避免同时使用两个映射或其他映射,因为您正在使用两种不同类型的密钥(除非您决定使用 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();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-30
      • 2021-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多