有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

servlet从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) 个答案

  1. # 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);
        }
    }
    

    你不需要在e.nextElement()之后的toString()。它将只给您String,因为您使用的是泛型类型


    作为补充说明,在这种情况下,我更愿意使用while循环,因为迭代的数量不是固定的。下面是for-loop的等效while循环版本:-

    {
        Enumeration<String> e = request.getParameterNames();
    
        while (e.hasMoreElements()) {
            String elem = e.nextElement();
            if(!"James".equalsIgnoreCase(elem)) {
                list.add(elem);
            } 
        }
    
    }
    
  2. # 2 楼答案

    您在跳过多个元素的每个循环中调用nextElement()多次。您只需要调用nextElement()一次。类似于

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

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

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