如何找到两个字符串数组联盟 [英] How to Find Union of Two String Arrays

查看:133
本文介绍了如何找到两个字符串数组联盟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到两个字符串数组的结合。我创建了一个新的数组,并复制了首盘的所有数据到新的数组。我无法将来自第二组信息到新的数组。

我需要使用循环来搜索第二阵列,并找到重复的。我不断收到 ArrayIndexOutOfBoundsException异常

下面是我目前的code:

 静态的String []联盟(字符串[] SET1,字符串[]设定2){
    工会字符串[] =新的String [set1.length + set2.length];    INT I = 0;
    INT CNT = 0;    对于(INT N = 0; N< set1.length; N ++){
        工会[I] =设置1 [I]
        我++;
        CNT ++;
    }    为(中间体m为0; M&下; set2.length; M +){
        为(中间体p值= 0; P&下; union.length,P ++){
            如果(SET2 [M]!=工会[P]){
                工会[I] = SET2 [M]。
                我++;
            }
        }
    }
    CNT ++;    工会=缩小(工会,CNT);    返回工会;
}


解决方案

使用一组做交集或联盟的标准方法。您应该使用设置类的集合框架。

为您的两个数组2 ArrayList的对象。结果
 定义一组对象。结果
 同时添加使用ArrayList的物体进入设置的addAll 方法。

作为集保存独特的元素,集合形成的联合
    两个数组。

  //推阵列在列表中。
  清单<串GT; list1的=新的ArrayList<串GT;(Arrays.asList(stringArray1));
  清单<串GT;列表2 =新的ArrayList<串GT;(Arrays.asList(stringArray2));  HashSet的<串GT;设置=新的HashSet<串GT;();  //在集合添加的列表。
  set.addAll(list1的);
  set.addAll(列表2);  //将其转换回数组。
  的String [] = unionArray set.toArray(新的String [0]);

I am trying to find the union of two string arrays. I have created a new array and have copied all the data from the first set into the new array. I am having trouble adding the information from the second set into the new array.

I need to use loops to search the second array and find the duplicates. I keep getting an ArrayIndexOutOfBoundsException.

Here is my current code:

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;
}

解决方案

The standard way of doing intersections or unions is using a set. You should use the Set class from collections framework.

Create two arraylist objects for your two arrays.
Define a Set object.
Add both the arraylist objects into the Set using addAll method.

As set holds unique elements, the set forms the union of both arrays.

  //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]);       

这篇关于如何找到两个字符串数组联盟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆