1

As I understand, there is a option in java to insert a new key to HashTable. This done by:

 Hashtable<String,String> hashTable=new Hashtable<String,String>();
 hashTable.put("Donald", "Trump");

Where donald is the key, and Trump is the value. If I want to add the value "TrumpY" to "Donald", than I use the same operation:

 hashTable.put("Donald", "TrumpY");

I have a question about the time complexity of this operation. As I understand the time complexity is O(1). But this is relavant for the first and the second operation? because the first need to add a new key to the hash table, and the second need to add only a value to key that already exists.

1
  • 2
    The second operation does not add a value to a key that already exists, it replaces it. Commented Feb 28, 2013 at 14:43

2 Answers 2

3

To find the slot where the value has to be added, the Map must find the position of this slot. To do this it uses the hashcode of the key. Depending on the underlying implementation there may be collision handling (chaining), ... So if the key already exists the second operation usually takes the time of hash computation + lookup + setting of the value requires.

Read more about the subject: http://en.wikipedia.org/wiki/Hash_table

Sign up to request clarification or add additional context in comments.

4 Comments

But what with the case that you add a new key (not just value), it doesn't take more time?
Adding a new key can take more time if there is not enough room left, depends on the underlying implementation and initial settings (capacity, ...). Read the Wikipedia article and you will start to understand how it works.
Finding the right slot in a hashtable for a key is functionally the same whether inserting or updating the value.
If the key already exists there is less work to do because the map now already contains the required structures (list, capacity...)
0

Inserting a key for the first time is going to take more time as it must create a new instance of java.util.Hashtable.Entry.

Whereas in the case of replacing the existing value for a key, it only has to assign the new value to the value reference in the already existing Entry instance.

2 Comments

Thank you, and what the time complexity of create a new instance of java.util.Hashtable.Entry?
More or less constant (depends on the JVM, available memory, GC ...)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.