我无法获得两个阵列列表的联盟

时间:2012-10-11 03:30:54

标签: java

public static <E> ArrayList<E> union
        (ArrayList<E>array1, ArrayList<E>array2)
{
  //arrayUnion will be the arrayList that will be returned
  ArrayList <E> arrayUnion  = new ArrayList <E>(array1);   
  arrayUnion.addAll(array2);
  E current;

  for(int i = 0; i < arrayUnion.size(); i++)
  {
      for(int j = 0; j < arrayUnion.size(); j++)
      {
          current = arrayUnion.get(i);
          if(current.equals(arrayUnion.get(j)))
          {
              arrayUnion.remove(j);
          }
      }
  }

      return arrayUnion;
}

对于我对此方法的测试,这是输出:

  

第一个列表是[ww,ee,rr,t,yy]

     

第二个清单是[ww,ss,ee,dd]

     

两个ArrayLists的并集是:[ee,t,ww,dd]

出了什么问题......?我已经被困在这个问题太久了,我再也不想听到联盟这个词了。 Plz帮助

4 个答案:

答案 0 :(得分:4)

您可以使用Set来获取联盟,它会更好地处理它。您应该注意的唯一想法是它可能会改变元素的顺序。

以下是一个例子:

    List<String> setA = new ArrayList<String>();
    List<String> setB = new ArrayList<String>();

    setA.add("aa");
    setA.add("bb");
    setA.add("cc");

    setB.add("dd");
    setB.add("ee");
    setB.add("ff");

    Set<String> union = new HashSet<String>();
    union.addAll(setA);
    union.addAll(setB);

    System.out.println(setA);
    System.out.println(setB);
    System.out.println(union);

答案 1 :(得分:1)

你会立即删除第一个元素(或i = j的任何元素),因为它等于它自己。

答案 2 :(得分:0)

您可以改变您的方式。将array1的所有元素添加到arrayUnion。然后迭代它并为每个项目检查它是否在array2中(使用array2.contains(<E>))。如果不存在,则删除它并最终得到联合: - )

public static <E> ArrayList<E> union(ArrayList<E> array1,
        ArrayList<E> array2) {
    // arrayUnion will be the arrayList that will be returned
    ArrayList<E> arrayUnion = new ArrayList<E>(array1);
    // arrayUnion.addAll(array2);
    E current;

    for (int i = 0; i < arrayUnion.size(); i++) {       
            current = arrayUnion.get(i);
            if(!array2.contains(current)){
                arrayUnion.remove(current);
            }
    }

    return arrayUnion;
}

答案 3 :(得分:0)

您的代码必须检查当前项目是否已自行检查。如果不是,则必须删除该项目并将j减少为{1}},因为您必须再次检查j处替换的项目。我已修改您的代码以适合您的情况。只需查看要删除的项目的条件检查。

public static <E> ArrayList< E > union( ArrayList< E > array1, ArrayList< E > array2 ) {
    // arrayUnion will be the arrayList that will be returned
    ArrayList< E > arrayUnion = new ArrayList< E >( array1 );
    arrayUnion.addAll( array2 );
    E current;

    for ( int i = 0; i < arrayUnion.size( ); i++ ) {

        for ( int j = 0; j < arrayUnion.size( ); j++ ) {
            current = arrayUnion.get( i );

            if ( i != j && current.equals( arrayUnion.get( j ) ) ) {
                arrayUnion.remove( j );
                --j;// This is set to check the item which replace the removed item at previous statement
            }
        }
    }

    return arrayUnion;
}