iterating through Enumeration of hastable keys throws NoSuchElementException error

后端 未结 7 907
没有蜡笔的小新
没有蜡笔的小新 2021-02-11 11:50

I am trying to iterate through a list of keys from a hash table using enumeration however I keep getting a NoSuchElementException at the last key in list?

Hasht         


        
相关标签:
7条回答
  • 2021-02-11 12:23

    You call nextElement() twice in your loop. This call moves the enumeration pointer forward. You should modify your code like the following:

    while (e.hasMoreElements()) {
        String param = e.nextElement();
        System.out.println(param);
    }
    
    0 讨论(0)
  • 2021-02-11 12:32

    Each time you do e.nextElement() you skip one. So you skip two elements in each iteration of your loop.

    0 讨论(0)
  • 2021-02-11 12:33

    You're calling nextElement twice in the loop. You should call it only once, else it moves ahead twice:

    while(e.hasMoreElements()){
        String s = e.nextElement();
        System.out.println(s);
    }
    
    0 讨论(0)
  • 2021-02-11 12:34

    You're calling e.nextElement() twice inside your loop when you're only guaranteed that you can call it once without an exception. Rewrite the loop like so:

    while(e.hasMoreElements()){
      String param = e.nextElement();
      System.out.println(param);
    }
    
    0 讨论(0)
  • 2021-02-11 12:36

    You are calling nextElement twice. Refactor like this:

    while(e.hasMoreElements()){
    
    
    String param = (String) e.nextElement();
    System.out.println(param);
    }
    
    0 讨论(0)
  • 2021-02-11 12:43
    for (String key : Collections.list(e))
        System.out.println(key);
    
    0 讨论(0)
提交回复
热议问题