Search code examples
javahashtable

Not able to add key to Dictionary after I remove all keys


I am able to add key to dictionary , and then Keep on iterate through loop I am removing all the values from Dictionary , However Once if I am trying to add any key in dictionary , it seems it does not add

here is code

public static void main(String[] args) {


        Dictionary dict = new Hashtable();
           dict.put("1", "Aniruddha");
           dict.put("2", "Anir");
           dict.put("3", "Anirdha");
           dict.put("4", "Anuddha");

          for(Enumeration key = dict.keys(); key.hasMoreElements();)
          {
              dict.remove(key);
          }

          dict.put("5", "swew");
          System.out.println(dict.get("5"));
       }

I am not getting Output for key "5" :(

Can anyone help me to improve code ?


Solution

  • You're not call Enumeration#nextElement, so you are constantly stuck before the first element in your for-loop

    Instead, you could use while-loop, for example...

    Dictionary<String, String> dict = new Hashtable<>();
    dict.put("1", "Aniruddha");
    dict.put("2", "Anir");
    dict.put("3", "Anirdha");
    dict.put("4", "Anuddha");
    
    Enumeration<String> keys = dict.keys();
    while (keys.hasMoreElements()) {
        String theRealKey = keys.nextElement();
        dict.remove(theRealKey);
    }
    
    dict.put("5", "swew");
    System.out.println(dict.get("5"));
    

    As a side not, unless you're modifying the Dictionary through multiple threads, you really shouldn't use HashTable (or Dictionary), but instead use Map and HashMap