日期:2014-05-20  浏览次数:20614 次

请大家来看一道题~~
有两个数组,要将两个数组里面的元素进行比较,判断如果第一个数组里面没有的东西,从第二个数组中添加到第一个数组,然后进行输入~  
比如   string[]   A   中有     a,b,c,d
String[]   B   中有   b,d,f,g         比较两个数组的元素,把A中没有的元素添加进去,如何做呢???     我想了一天啊,关键地方还是不会写~请大家赐教啊~~

------解决方案--------------------
import java.util.*;

public class Test1
{
public static List <String> makeList(String[] strs){
List <String> list=new ArrayList <String> ();
for(int i=0;i <strs.length;i++)list.add(strs[i]);
return list;
}
public static void main(String[] args)
{
String[] A={ "a ", "b ", "c ", "d "};
String[] B={ "b ", "d ", "f ", "g "};
List <String> list1=makeList(A);
List <String> list2=makeList(B);
for(String s:list2){
if(!list1.contains(s))
list1.add(s);
}
System.out.println(list1);
}
}
------解决方案--------------------
import java.util.*;

public class HashSetTest {
public static void main(String[] args) {
String[] a = { "a ", "b ", "c ", "d ", "e ", "f "};
String[] b = { "d ", "e ", "f ", "g ", "h ", "i "};

HashSet <String> mySet = new HashSet <String> ();
for (int i=0; i <a.length; i++)
mySet.add(a[i]);
for (int i=0; i <b.length; i++)
mySet.add(b[i]);

String[] c = mySet.toArray(new String[0]);
for (int i=0; i <c.length; i++)
System.out.print(c[i] + " ");
}
}
--------------------------------------------
output is :
f g d e b c a h i