Choosing the perfect data structure for the below data in java

后端 未结 2 1903
难免孤独
难免孤独 2021-01-23 15:33

I have to choose one data structure for my need below i am explaining the conditions there are following values

abc,def,rty,ytr,dft   which all are map to row R         


        
2条回答
  •  有刺的猬
    2021-01-23 16:14

    Key-value pairs can be accessed in O(1) using a HashMap. However if you use HashMap then updating the value will be painful because Strings are immutable. This means you will have to check all entry sets and if the value matches update it. So you could create a helper class for the value and let all keys point to an instance of this class. Here is a stub with the most important functions, I guess you can add the rest yourself.

    public class MyDataStructure {
    
      private Map key_value = new HashMap();
      private Map value_MyValue = new HashMap();
    
      public void set(String key, String value) {
        MyValue v = value_MyValue.get(value);
        if (v == null) { // should rarely happen, could check with containsKey
          v = new MyValue(value);
          value_MyValue.put(v);
        }
        key_value.put(key, v);
      }
    
      public String get(String key) {
        return key_value.get(key).getValue(); // key might not exist
      }
    
      public String changeValue(String oldValue, String newValue) {
        MyValue v = value_MyValue.remove(oldValue); // oldValue might not exist
        v.setValue(newValue); 
        value_MyValue.put(newValue, v);
        // will not work if newValue already exists... then you will have to merge
      }
    
      private class MyValue() {
        private String value;
        public MyValue(String value) {
          this.value = value;
        }
        public String getValue() {
          return value;
        }
        public void setValue(String value) {
          this.value = value;
        }
      }
    }
    

提交回复
热议问题