首页 > 编程语言 > 详细

转: java 双向map

时间:2014-03-30 12:20:53      阅读:426      评论:0      收藏:0      [点我收藏+]
bubuko.com,布布扣
package tools;

import java.util.HashMap;

public class DuplexMap<K,V> {
    class Entry{
        K k;
        V v;
        public Entry(K k,V v){
            this.k=k;
            this.v=v;
        }
        public K getK() {
            return k;
        }
        public V getV() {

            return v;
        }
        public void setK(K k) {
            this.k = k;
        }
        public void setV(V v) {
            this.v = v;
        }
    }
    private HashMap<K,Entry> kEntyMap=new HashMap<K,Entry>();
    private HashMap<V,Entry> vEntyMap=new HashMap<V,Entry>();
    public boolean contains(K k){
        return kEntyMap.containsKey(k);
    }
    public boolean containsValue(V v){
        return vEntyMap.containsKey(v);
    }
    public V getByKey(K k){
        Entry e=kEntyMap.get(k);
        if(e==null){
            return null;
        }
        return e.getV();
    }
    public K getbyValue(V v){
        Entry e=vEntyMap.get(v);
        if(e==null){
            return null;
        }
        return e.getK();
    }
    public boolean put(K k,V v){
        if(k==null||v==null){
            return false;
        }
        Entry e=new Entry(k, v);
        if(contains(k)){
            remove(k);
        }
        if(containsValue(v)){
            removeByValue(v);
        }
        kEntyMap.put(k, e);
        vEntyMap.put(v, e);
        return true;
    }
    public V remove(K k){
        Entry e=kEntyMap.remove(k);
        if(e==null){
            return null;
        }
        vEntyMap.remove(e.getV());
        return e.getV();
    }
    public K removeByValue(V v){
        Entry e=vEntyMap.remove(v);
        if(e==null){
            return null;
        }
        kEntyMap.remove(e.getK());
        return e.getK();
    }
}
bubuko.com,布布扣

转自:http://www.oschina.net/code/snippet_83492_4187

转: java 双向map,布布扣,bubuko.com

转: java 双向map

原文:http://www.cnblogs.com/ibearpig/p/3633611.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!