Search code examples
javahashtable

Java Hashtable : one key - two value, how to get both of them?


My problem is that I have an Hashtable and I end up with some key having two values. I would like to get both of these value, so I can see which one I want and take it.

Here is an exemple :

Hashtable<String, String> myTable = new Hashtable<>();
myTable.put("key1", "value1");
myTable.put("key1", "value2");
System.out.println(myTable.get("key1"));
//output : value2

How to retrieve both of the value ?

Thank you for your help !


EDIT : In my tests, the HashTable can't store 2 values like this but I assure that in my project where I have a (I believe) code that does the same thing. When, after my algorithm has ran I System.out.prinln(myTable) it does show multiple time the same key with differents value.


Solution

  • It depends on the way to create a HashTable, in your example. You create a HashTable maps a String to a String, then because the value is a String, you cannot expect the table can store multiple values on one key. When you do the second put method, it will find the key with value key1 and replace the previous value which is mapped to this key to the new one.

    If you want to store multiple values on one key, think about the list which will hold multiple values for your key. Here is an example to map a key with a type of String to multiple String values:

    Hashtable<String, ArrayList<String>> myTable = new Hashtable<>();
    ArrayList<String> listValue = new ArrayList<>();
    listValue.add("value1");
    listValue.add("value2");
    myTable.put("key1", listValue); 
    System.out.println(myTable.get("key1")); // get all values of the key [value1, value2]
    System.out.println(myTable.get("key1").get(0)); // get the first value of this key, value1
    System.out.println(myTable.get("key1").get(1)); // get the second value of this key, value2
    

    It is recommended to use HashMap over a HashTable.