本帖最后由 秦碧 于 2012-2-7 18:37 编辑
import java.util.*;
class HashSetTest
{
public static void main(String[] args)
{
HashSet hsa=new HashSet();
hsa.add(1);
hsa.add(2);
hsa.add(3);
hsa.add(4);
HashSet hsb=new HashSet();
hsb.add(1);
hsb.add(2);
hsb.add(5);
hsb.add(6);
HashSet hs=new HashSet();
hs=combine(subtract(hsa,hsb),subtract(hsb,hsa)); //(A-B)U(B-A)
print(hs);
}
public static HashSet subtract(HashSet hsa,HashSet hsb) //hsa-hsb
{
HashSet hs=new HashSet();
for (Iterator it=hsa.iterator();it.hasNext() ; )
{
Object obj=it.next();
if (!hsb.contains(obj))
{
hs.add(obj);
}
}
return hs;
}
public static HashSet combine(HashSet hsa,HashSet hsb) //hsa U hsb
{
HashSet hs=new HashSet();
hs.addAll(hsa);
for (Iterator it=hsb.iterator();it.hasNext() ; )
{
Object obj=it.next();
if (!hs.contains(obj))
{
hs.add(obj);
}
}
return hs;
}
public static void print(HashSet hs) //遍历打印
{
for (Iterator it=hs.iterator();it.hasNext() ; )
{
System.out.print(it.next()+" ");
}
}
} |