Writing a Key Value Store

Writing a Key Value Store
The purpose of this exercise is to write a basic key value store. It should use string keys and string values only. The following operations should be supported:

set
get
delete
keys
Function explanations


SET


Set key to hold the string value. If key already holds a value, it is overwritten, regardless of its existence. The method should return the string "OK"


GET


Get the value of a key. If the key does not exist, return the string "nil"


DELETE


Removes the specified keys. A key is ignored if it does not exist. Returns the number of keys that were removed. This is a variadic function and should accept any number of keys as arguments.


delete("1","2") or delete("1") or delete("1","3","4"...)

delete(Object... arg) => arg behave as array.


public interface keyValueStore{
  
  HashMap<String, String> map = HashMap<String,String>();
  
  //performance of set ? O(1).
  public String set (String key, String value) {
      if (map.containsKey(key)) {
          map.remove(key);
          map.put(key,value);
      } else {
          map.put(key, value);
      }
    
      return "OK";
  }
  
  // find a way to diminish your code a little.
  // get() => O(1)
  public String get (String key) {
      return map.get(key);
  }
  
  //delete("1","2")
  //performance of delete ? O(n2)
  
  // 100k max . delete 1 => (100k)
  
  //clean your method.
  public String delete (String... keys) {
      if (keys == null || keys.length == 0)
            return 0;
      int count = 0;
      for (String temp : keys) {
          
          if (map.get(key) != null) {
              map.remove(key);
                  count++;
          }
      
      }
    
    return count;
  }
  
}


advantage of interface:

We can have multiple implementation of one interface.



Interfaces are a way of decoupling separate software components. Sure, you may use an Oracle data base to store all your data today so why not dispense of all your DAO interfaces?

The answer is that strongly coupling to anything may come back and bite you in the future. What if next year you want to use some cloud service to store data? If you coded to a DAO interface you can simply introduce a new cloud implementation and plug it straight in. Your app is loosely coupled so doesn't need to change.




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值