跳过Enumeration Java中的元素

时间:2012-12-18 08:39:58

标签: java servlets httprequest

我想使用Enumeration跳过某个请求参数。我使用下面的代码,但它没有给我想要的结果。任何人都可以告诉我如何跳过Enumeration中的元素或者下面的代码是错误的?

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

3 个答案:

答案 0 :(得分:3)

您正在跳过多个元素的每个循环多次调用nextElement()。您只需拨打nextElement()一次。有点像...

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

答案 1 :(得分:1)

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

首先应将元素存储在String类型中,然后进行比较: -

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);
        } 
    }

}

答案 2 :(得分:1)

因为每当您call nextElement()时,每次调用此方法都会从枚举中获取下一个元素。如果在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);
    }
}