从ArrayList中删除元素

我必须从ArrayList删除元素,但我还没有完成它。 我必须删除的元素也可以在ArrayList 。 简而言之,我必须从另一个arrays列表中删除一个arrays列表。 例如假设

 ArrayList arr1= new ArrayList(); ArrayList arr2 = new ArrayList(); arr1.add("1"); arr1.add("2"); arr1.add("3"); arr2.add("2"); arr2.add("4"); 

现在,我必须从arr1中删除arr2中的元素。 那么,我的最终答案为1和3.需要做什么?

阅读删除两个列表中的常用元素Java


使用下面的代码

 List resultArrayList = new ArrayList(arr1); resultArrayList.removeAll(arr2); 

或者可以通过

 arr1.removeAll(arr2) 

经过SO评论

我使用了以下代码

 ArrayList arr1= new ArrayList(); ArrayList arr2 = new ArrayList(); arr1.add("1"); arr1.add("2"); arr1.add("3"); arr2.add("2"); arr2.add("4"); System.out.println("Before removing---"); System.out.println("Array1 : " + arr1); System.out.println("Array2 : " + arr2); System.out.println("Removing common ---"); List resultArrayList = new ArrayList(arr1); resultArrayList.removeAll(arr2); System.out.println(resultArrayList); 

并获得输出

 Before removing--- Array1 : [1, 2, 3] Array2 : [2, 4] Removing common --- [1, 3] 

那么什么不适合你?

阅读更多关于如何从另一个列表中删除一个列表的重叠内容?

将new arr作为最终排序数组

 for(int i=0;i 

您可以使用removeAll()函数

 /** * Removes from this list all of its elements that are contained in the * specified collection. * * @param c collection containing elements to be removed from this list * @return {@code true} if this list changed as a result of the call * @throws ClassCastException if the class of an element of this list * is incompatible with the specified collection * (optional) * @throws NullPointerException if this list contains a null element and the * specified collection does not permit null elements * (optional), * or if the specified collection is null * @see Collection#contains(Object) */ public boolean removeAll(Collection c) { return batchRemove(c, false); } 

要从其他中删除一个副本,请使用此方法

  int arr1Size = arr2.size(); int arr2Size = arr2.size(); for (int i = 0; i < arr1Size; i++) { for (int j = 0; j < arr2Size; j++) { if (arr1.get(i).contains(arr2.get(j))) { arr1.remove(i); } } } System.out.print(arr1); 

好清楚:

如果你的列表由基本元素组成,比如String等,你需要做的就是使用

 list2.removeAll(list1); 

假设不是这种情况意味着您从custum对象创建了一个列表 – 上述方法不起作用,这是由于项目比较的性质。 它使用object.equals方法,该方法默认检查这是否是另一个列表中对象的相同实例(它可能不是)

所以为了使它能够工作,你需要覆盖自定义对象equals方法。

示例 – 根据电话号码测试2个联系人是否相同:

 public boolean equals(Object o) { if (o==null) { return false; } if (o.getClass()!=this.getClass()) { return false; } Contact c=(Contact)o; if (c.get_phoneNumber().equals(get_phoneNumber())) { return true; } return false; } 

现在,如果你使用

 list2.removeAll(list1); 

它将根据所需属性(在基于电话号码的示例中)比较项目,并将按计划工作。