送交者: 松鼠 于 2005-11-10, 09:43:59:
回答: Java HashSet Problem. 由 松鼠 于 2005-11-10, 00:21:15:
/*# Script Name: testRemove.java
# Script Version:
# Date:
# Author: Ben@fadshop.net
# Description:
#
*/
import java.util.*;
class testRemove
{
public HashSet set;
public testRemove(){
Integer I;
set = new HashSet();
set.add(new Integer(1));
set.add(new Integer(-1));
set.add(new Integer(2));
set.add(new Integer(3));
set.add(new Integer(4));
set.add(new Integer(5));
}
void remove1(){
for (Iterator term = set.iterator(); term.hasNext(); ) {
Integer o = (Integer) term.next();
System.out.println("Got " + o);
if (o.intValue() == -1)
set.remove(o);
}
}
void remove2(){
Integer o=null, oldo;
for (Iterator term = set.iterator(); term.hasNext(); ) {
if( (o != null) && ((o.intValue() == -1)) )
{
oldo = o;
o = (Integer) term.next();
set.remove(oldo);
}
else
o = (Integer) term.next();
System.out.println("Got " + o);
}
}
public static void main(String[] args)
{
try{
testRemove t = new testRemove();
System.out.println("origin set:" + t.set);
// t.remove1();
t.remove2();
System.out.println("After remove action:" + t.set);
}catch(Exception e) {e.printStackTrace();}
}
}
You can get it directly from the given link:
http://fadshop.net/squirrel/test/testRemove.java