1

I have an issue where I am creating an arraylist and adding multiple arraylists to this one. At some points in the program I need to remove these lists from the one central list. I have been using removeAll(); but this removes all instances of one element. For example the arraylist can contain (1,2,3,4,5) and one can add the list (1,2,3) to it. Yet when you go to remove this list the resultant list now contains (4,5) while it is desired for it to contain (1,2,3,4,5). How can that be accomplished? Thanks for any help.

multifractal
  • 119
  • 1
  • 5

1 Answers1

1

Sounds like you should just use remove instead of removeAll. You can put it in a loop to remove all the elements from a collection:

ArrayList<Integer> bigList = new ArrayList<Integer>();

// Put multiple smaller lists into big list
bigList.addAll(list1);
bigList.addAll(list2);
bigList.addAll(list3);

// Remove list2's elements from bigList
for (Integer i : list2) {
  bigList.remove(i);
}

Update:

Runnable version:

import java.util.*;

public class RemoveTest {
  public static void main(String[] args) {
    List<Integer> list1 = Arrays.asList(1, 2, 3);
    List<Integer> list2 = Arrays.asList(1, 2, 3, 4, 5);
    List<Integer> list3 = Arrays.asList(9);

    ArrayList<Integer> bigList = new ArrayList<Integer>();

    // Put multiple smaller lists into big list
    bigList.addAll(list1);
    bigList.addAll(list2);
    bigList.addAll(list3);

    // Remove list2's elements from bigList
    for (Integer i : list2) {
      bigList.remove(i);
    }

    System.out.println(bigList);
    // Result:
    // [1, 2, 3, 9]
  }
}
DaoWen
  • 32,589
  • 6
  • 74
  • 101
  • @OQJF - Click the link I gave for `remove`. Notice it says it removes a _single instance_ of the given object, whereas `removeAll` removes _all instances_ of _all given objects_. Did you test my code? (I actually haven't yet—I was in the middle of typing a runnable test.) – DaoWen Mar 20 '13 at 02:38
  • Sorry, that's my fault. tested it – OQJF Mar 20 '13 at 02:43
  • @OQJF - No problem. I had to go double-check the docs about the behavior of `remove` vs `removeAll`, which is why I included the link. I just tested my runnable example and it seems to be working. – DaoWen Mar 20 '13 at 02:44
  • Definitely, remove just remove the first element and removeAll will remove all the element. It will change the elements order but the result is good. – OQJF Mar 20 '13 at 02:48
  • Yea this may be easier than a 2-d list...I will give it a try. Thanks for the time. – multifractal Mar 20 '13 at 15:11