2

I am wondering if there is a data structure that can store one to one relationship in Java.

For example, for mapping the month of the year with its number and vice versa.

I know I can use two HashMaps, but I want to know if there is another data structure that also checks the value when I put a new pair.

4

3 回答 3

3

但是,标准 Java 中没有。但是,如果您可以使用 3rd 方库,则可以使用Guava 。BiMap

双映射(或“双向映射”)是一种映射,它保留其值的唯一性以及其键的唯一性。此约束使 bimap 能够支持“反向视图”,这是另一个 bimap,包含与此 bimap 相同的条目,但具有相反的键和值。

于 2013-10-03T15:43:52.413 回答
0

没有数据结构,但我认为您可以使用参数化的 Pair 来完成此任务。这门课很受欢迎,你会在互联网上学习。

这是关于SO的一个: 通用对类

于 2013-10-03T15:45:35.847 回答
0

最近需要一个解决方案,但不想依赖插件......所以我扩展了基础 Java 类。此实现不允许null值。

public class OneToOneMap<K,V> extends HashMap<K,V> {
    public OneToOneMap() {
        super();
    }
    public OneToOneMap(int initialCapacity) {
        super(initialCapacity);
    }
    public OneToOneMap(int initialCapacity, float loadFactor) {
        super(initialCapacity, loadFactor);
    }
    public OneToOneMap(Map<? extends K, ? extends V> m) {
        super(m);
        dedup();
    }

    @Override
    public void putAll(Map<? extends K, ? extends V> m){
        super.putAll(m);
        dedup();
    }

    @Override
    public V put(K key, V value) {
        if( key == null || value == null ) return null;
        removeValue(value);
        return super.put(key,value);
    }

    public K getKey( V value ){
        if( value == null || this.size() == 0 ) return null;
        Set<K> keys = new HashSet<>();
        keys.addAll(keySet());
        for( K key : keys ){
            if( value.equals(get(key) )) return key;
        }
        return null;
    }
    public boolean hasValue( V value ){
        return getKey(value) != null;
    }
    public boolean hasKey( K key ){
        return get(key) != null;
    }

    public void removeValue( V remove ){
        V value;
        Set<K> keys = new HashSet<>();
        keys.addAll(keySet());
        for( K key : keys ){
            value = get(key);
            if( value == null || key == null || value.equals(remove)) remove(key);
        }        
    }
    //can be used when a new map is assigned to clean it up
    public void dedup(){
        V value;
        Set<V> values = new HashSet<>();
        Set<K> keys = new HashSet<>();
        keys.addAll(keySet());
        for( K key : keys ){
            value = get(key);
            if( value == null || key == null || values.contains(value) ) remove(key);
            else values.add(value);
        }
    }
}
于 2017-10-28T22:49:42.123 回答