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.
Asked
Active
Viewed 2,500 times
1
-
1Post some code that you have tried... – Iswanto San Mar 20 '13 at 02:30
-
I don't think you can find a good resolution to fix it, because the mechanism of replaceAll. – OQJF Mar 20 '13 at 02:35
-
Why don't you use the 2 dimension array list: http://stackoverflow.com/questions/5022824/how-to-fill-a-two-dimensional-arraylist-in-java-with-integers – user650749 Mar 20 '13 at 02:38
-
Yeah, that's my suggestion too. – OQJF Mar 20 '13 at 02:39
-
Please check the answer, I tested that it works. – OQJF Mar 20 '13 at 02:49
1 Answers
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
-
-
@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