0

I'm looking to build a hash table where multiple String keys that share the same Byte array value are merged into one value with multiple keys. This is so the value isn't stored over and over again with different values. Adding a key with a value should also overwrite any existing key with the same name, but keep the value if it has a different key as well, but delete it when there is no other key.

EDIT: How do I build this data structure? For example, if I insert "hello" with a value, then add "World" with the same value, I would like the structure to something along the lines of [[Hello, World], Value] instead of [Hello, Value], [World, Value]. I tried using a list as my hashkey, but found I couldnt recall the value. Here is my code:

HashMap<List<String>, byte[]> map = new HashMap<List<String>, byte[]>();

public void storeByte (String id, int value) {
      byte[] byteValue = new byte[value];
      ArrayList<String> idlist = new ArrayList<String>();
      idlist.add(id);
      map.put(idlist, byteValue);
      System.out.println(map);
  }

 public byte[] fetchByte(String id) {
      ArrayList<String> idlistsearch = new ArrayList<String>();
      idlistsearch.add(id);
      byte[] output = map.get(id);
      if(map.containsKey(idlistsearch)){
          output = map.get(id);
          } else {
              return null;
          } 
      return output;

I hope this makes sense,

Thank you.

jaffa507
  • 1
  • 1
  • 1
    You might need to give a clear example of what you are trying to store and how it should be handled. From your description it's not easy to determine what you are trying to achieve. – Bobulous May 17 '15 at 15:02
  • 1
    What's your question? – Radiodef May 17 '15 at 15:03

1 Answers1

0

i'm looking to build a hash table where multiple String keys that share the same Byte array value are merged into one value with multiple keys.

This is how HashMap and Hashtable works. There isn't any other option builtin.

When you define

byte[] bytes =

this is a reference, not an actual object. When you add this reference to the map, you are adding this reference and it can be added as many times as you like, but there is only one copy.

if I insert "hello" with a value, then add "World" with the same value,

You can do

byte[] bytes =
map.put("Hello", bytes);
map.put("World", bytes);

This is two keys and only one value.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130