java中数据库类_Java中简单的类似数据库的集合类

我认为你可以用以下两个类来实现你所需要的.虽然它确实涉及两个地图,但它们不会暴露给外部世界,因此不应该让它们失去同步.至于两次存储相同的“事实”,我认为你不会在任何有效的实现中解决这个问题,无论事实是在这里显式地存储两次,还是隐含在数据库创建索引时在2个表上使连接更有效.您可以向magicset添加新内容,它将更新两个映射,或者您可以向magicmapper添加内容,然后将自动更新反向地图.女朋友现在叫我睡觉所以我不能通过编译器运行它 – 它应该足以让你开始.你想解决什么难题?

public class MagicSet {

private Map forward;

private R r;

private Set set;

public MagicSet(Map forward, R r) {

this.forward = map;

this.r = r;

this.set = new HashSet();

}

public void add(L l) {

set.add(l);

forward.put(l,r);

}

public void remove(L l) {

set.remove(l);

forward.remove(l);

}

public int size() {

return set.size();

}

public in contains(L l){

return set.contains(l);

}

// caution, do not use the remove method from this iterator. if this class was going

// to be reused often you would want to return a wrapped iterator that handled the remove method properly. In fact, if you did that, i think you could then extend AbstractSet and MagicSet would then fully implement java.util.Set.

public Iterator iterator() {

return set.iterator();

}

}

public class MagicMapper { // note that it doesn't implement Map, though it could with some extra work. I don't get the impression you need that though.

private Map forward;

private Map> inverse;

public MagicMapper() {

forward = new HashMap;

inverse = new HashMap>;

}

public R getForward(L key) {

return forward.get(key);

}

public Set getBackward(R key) {

return inverse.get(key); // this assumes you want a null if

// you try to use a key that has no mapping. otherwise you'd return a blank MagicSet

}

public void put (L l, R r) {

R oldVal = forward.get(l);

// if the L had already belonged to an R, we need to undo that mapping

MagicSet oldSet = inverse.get(oldVal);

if (oldSet != null) {oldSet.remove(l);}

// now get the set the R belongs to, and add it.

MagicSet newSet = inverse.get(l);

if (newSet == null) {

newSet = new MagicSet(forward, r);

inverse.put(r,newSet);

}

newSet.add(l); // magically updates the "forward" map

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值