首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

为什么总是删除Vector的第二个元素呢?该怎么解决

2012-01-12 
为什么总是删除Vector的第二个元素呢? 以下代码原目的是想从Vector中,读一个组件删除一个组件,但是为什么

为什么总是删除Vector的第二个元素呢?

以下代码原目的是想从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, 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.Three

First 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.Three

Now, 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?

热点排行