将集合A和B中的元素合并到集合A中

packageLabEight;
importjava.util.*;
publicclassSetDemo{
publicstaticvoidmain(String[]args)
{
int[]a={2,5,9,13};
int[]b={1,3,6,9,15,21};
HashSetsetA=newHashSet();
HashSetsetB=newHashSet();
for(inti=0;i<a.length;i++)
{
//将数组a中元素添加到setA对象中
}
for(inti=0;i<b.length;i++)
{
//将数组b中元素添加到setB对象中
}
System.out.println("合并前集合A的数据:");
Iteratorit=setA.iterator();
while(it.hasNext())
{
System.out.print(it.next()+"");
}
//将setB中元素合并到setA中
System.out.println("\n合并后集合B的数据:");
it=setA.iterator();
while(it.hasNext())
{
System.out.print(it.next()+"");
}
}
}


 public static void main(String[] args) {
        int[] a={2,5,9,13};
        int[] b={1,3,6,9,15,21};
        //这里必须指定HashSet的类型
        HashSet<Integer> setA=new HashSet<Integer>();
        HashSet<Integer> setB=new HashSet<Integer>();
        for(int i=0;i<a.length;i++)
        {
            //将数组a中元素添加到setA对象中
            setA.add(a[i]);
        }
        for(int i=0;i<b.length;i++)
        {
            //将数组b中元素添加到setB对象中
            setB.add(b[i]);
        }    
        System.out.println("合并前集合A的数据:");
        Iterator it=setA.iterator();
        while(it.hasNext())
        {
            System.out.print(it.next()+"  ");
        }
        //将setB中元素合并到setA中
        //这里必须指定Iterator的类型
        Iterator<Integer> itB=setB.iterator();
        while(itB.hasNext())
        {
            setA.add(itB.next());
        }
        System.out.println("\n合并后集合A的数据:");
        it=setA.iterator();
        while(it.hasNext())
        {
            System.out.print(it.next()+"  ");
        }
    }

可以参考一下

setA.addAll(setB);

用集合的addAll方法,可以实现合并。
比如A.addAll(B)