Luke Mann Luke Mann - 2 months ago 7
Java Question

Java: See if ArrayList contains ArrayList with duplicate values

I'm currently trying to create a method that determine if an ArrayList(a2) contains an ArrayList(a1), given that both lists contain duplicate values (containsAll wouldn't work as if an ArrayList contains duplicate values, then it would return true regardless of the quantity of the values)

This is what I have: (I believe it would work however I cannot use .remove within the for loop)

public boolean isSubset(ArrayList<Integer> a1, ArrayList<Integer> a2) {
Integer a1Size= a1.size();
for (Integer integer2:a2){
for (Integer integer1: a1){
if (integer1==integer2){
if (a1Size==0){
return true;
return false;

Thanks for the help.


if you want remove elements from list you have 2 choices:

  • iterate over copy
  • use concurrent list implementation

see also:

btw why you don't override contains method ??

here you use simple Object like "Integer" what about when you will be using List< SomeComplexClass > ??

example with iterator over copy:

    List<Integer> list1 = new ArrayList<Integer>();
    List<Integer> list2 = new ArrayList<Integer>();

    List<Integer> listCopy = new ArrayList<>(list1);
    Iterator<Integer> iterator1 = listCopy.iterator();
    while(iterator1.hasNext()) {
        Integer next1 =;
        Iterator<Integer> iterator2 = list2.iterator();
        while (iterator2.hasNext()) {
            Integer next2 =;
            if(next1.equals(next2)) list1.remove(next1);

see also this answer about iterator:

Concurrent Modification exception

also don't use == operator to compare objects :) instead use equal method

about use of removeAll() and other similarly methods:

keep in mind that most classes that implements list interface don't override all methods from list interface - so you can end up with unsupported operation exception - thus I prefer "low level" binary/linear/mixed search in this case.