如何找到两个字符串数组的联合

use*_*866 1 java arrays

我试图找到两个字符串数组的联合.我创建了一个新数组,并将第一组中的所有数据复制到新数组中.我无法将第二组中的信息添加到新数组中.

我需要使用循环来搜索第二个数组并找到重复项.我一直在接受ArrayIndexOutOfBoundsException.

这是我目前的代码:

static String[] union(String[] set1, String[] set2) {
    String union[] = new String[set1.length + set2.length];

    int i = 0;
    int cnt = 0;

    for (int n = 0; n < set1.length; n++) {
        union[i] = set1[i];
        i++;
        cnt++;
    }

    for (int m = 0; m < set2.length; m++) {
        for (int p = 0; p < union.length; p++) {
            if (set2[m] != union[p]) {
                union[i] = set2[m];
                i++;
            }
        }
    }
    cnt++;

    union = downSize(union, cnt);

    return union;
}
Run Code Online (Sandbox Code Playgroud)

Sor*_*ter 7

做交叉或联合的标准方法是使用一套.您应该使用Set集合框架中的类.

为两个数组创建两个arraylist对象.
定义Set对象.
将两个arraylist对象添加到Set using addAll 方法中.

由于set包含唯一元素,因此该集合形成两个数组的并集.

  //push the arrays in the list.
  List<String> list1 = new ArrayList<String>(Arrays.asList(stringArray1));
  List<String> list2 = new ArrayList<String>(Arrays.asList(stringArray2));

  HashSet <String> set = new HashSet <String>();

  //add the lists in the set.
  set.addAll(list1);
  set.addAll(list2);

  //convert it back to array.
  String[] unionArray = set.toArray(new String[0]);       
Run Code Online (Sandbox Code Playgroud)