0

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.

Virgil
  • 5
  • 2
  • Also take a look at this: [hashmap vs. hashtable](https://stackoverflow.com/questions/40471/differences-between-hashmap-and-hashtable). – andrewJames Apr 11 '20 at 14:16
  • @andrewjames It partially answer. I think the problem comes from the fact that I work with Object and I constantly makes new ones. So it does not consider the keys to be the same thing. So I should probably rewrite this code – Virgil Apr 11 '20 at 14:21
  • Have you considered using a pair object as a value into your hash table – GilbertS Apr 11 '20 at 14:41
  • 1
    I didn't but now I do. It is, I think, the best solution. – Virgil Apr 11 '20 at 14:48

2 Answers2

0

In HashMap class, put function adds object if it isn't exist, if it's exist just updates the value. You can create another class to keep values;

class exampleValue {
    String v1, v2;

    exampleValue() {}
}

and

HashMap<String, exampleValue> h = new HashMap<>();

exampleValue v = new exampleValue();
v.v1 = "a";
v.v2 = "b";

h.put("key", v);

h.get("key").v1; //returns "a"
h.get("key").v2; //returns "b"  
Atahan Atay
  • 363
  • 2
  • 15
0

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.

Nam V. Do
  • 630
  • 6
  • 27