以下代码原目的是想从Vector中, 读一个组件删除一个组件, 但是为什么总是删除Vector的第二个元素呢? 如何改才能实现读一个组件, 删除一个组件呢? import java.util.Enumeration;
import java.util.Vector;public class Test {
public static void main(String[] args) {
String str = null;
Vector vec = new Vector(); vec.addElement("1.one");
vec.addElement("2.Two");
vec.addElement("3.Three");

Enumeration e = vec.elements();
while (e.hasMoreElements()) {
str = (String) e.nextElement();
System.out.println("send: " + str + " ");
vec.remove(str);

try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
// System.out.println(ex.getMessage());
}
}
System.out.println(vec.size());
}
}

解决方案 »

  1.   

    1, The second element in the vector is not removed.
    2, Enumeration e is directly linked to the Vector vec. It enumerates all the elements using the vector's internal counter. After you remove the first element in the vector, the counter for the remaining elements change.index    element
    0       1.one
    1       2.Two
    2       3.ThreeFirst call to e.nextElement() returns index 0, "1.one". The counter is set to 0.
    After remove("1.one"), the vector changed.
    index    element
    0        2.Two
    1        3.ThreeNow, if we call e.nextElement(), it will return the element with index 1. This is why you get "3.Three".e.hasMoreElements() also uses this counter to determine the end of enumeration.Are you clear now?
      

  2.   


    I want to print one element and then remove the element. How to modify this code for this function? Give me mroe direction!Thanks
      

  3.   

    You don't have to use Enumeration.int size =vec.size();for (int i=0; i<size; i++)
    {
    String str = (String)vec.remove(0);
    System.out.println(str);
    }
      

  4.   

    So much love to you! Thanks!
      

  5.   

    No love, points only, please. :P