2012-12-18 52 views
0

我想使用枚举跳过某个请求参数。我使用下面的代码,但它没有给我想要的结果。任何人都可以告诉我如何跳过Enumeration中的元素或下面的代码有什么问题?跳过枚举Java中的元素

for (Enumeration<String> e = request.getParameterNames(); e.hasMoreElements();) { 
     if("James".equalsIgnoreCase(e.nextElement().toString())) { 
      e.nextElement(); 
      continue; 
     } else { 
      list.add(e.nextElement().toString()); 
     } 
    } 

回答

3

您每次循环呼叫nextElement()多次跳过多个元素。您只需拨打nextElement()一次。喜欢的东西...

for (Enumeration<String> e = request.getParameterNames(); e.hasMoreElements();) { 
    String value = e.nextElement(); 
    if(!"James".equalsIgnoreCase(value)) { 
     list.add(value); 
    } 
} 
1

问题是,你在你的if调用e.nextElement()两次。这将消耗两个元素。

你应该存储在一个字符串的元素头型,然后做比较: -

for (Enumeration<String> e = request.getParameterNames(); e.hasMoreElements();) { 
    String elem = e.nextElement(); 
    if("James".equalsIgnoreCase(elem)) { 
     continue; 
    } else { 
     list.add(elem); 
    } 
} 

而你并不需要一个toString()e.nextElement()。它只会给你String,因为你使用的是泛型类型。


作为一个方面说明,我宁愿使用while循环在这种情况下,迭代的次数是不固定。下面是等价while循环版本的for-loop为: -

{ 
    Enumeration<String> e = request.getParameterNames(); 

    while (e.hasMoreElements()) { 
     String elem = e.nextElement(); 
     if(!"James".equalsIgnoreCase(elem)) { 
      list.add(elem); 
     } 
    } 

} 
1

因为每次当你callnextElement()所以每次调用此方法将枚举获得下一个元素。如果在Enumeration中没有对象,并且您将尝试获取它,您也可能会遇到异常。

NoSuchElementException - if no more elements exist. 

因此,只需更改您的代码并只需拨打nextElement()一次。

for (Enumeration<String> e = request.getParameterNames(); e.hasMoreElements();) { 
    String str= e.nextElement().toString(); 
    if("James".equalsIgnoreCase(str)) { 
     continue; 
    } else { 
     list.add(str); 
    } 
}