Assume that you have two Lists and you want to merge them somehow.
/* list1 consists of [1, 2, 3, 4, 5] and list2 consists of [6, 7, 8, 9]*/
/* I want to merge both lists*/
/* I can use addAll and add list2 at the end of list1*/
list1.addAll(list2);
/* if we take a look at list1 we will see*/
System.out.println(list1);
/* output is [1, 2, 3, 4, 5, 6, 7, 8, 9] */
If you take a look at the illustration above you'll see that red, green part of the sets and two blue part of the sets (elements of the intersection are used 2 times each) are obtained after addAll().
If we don't want elements of the second list to be added to the end of the first list then we can use addAll() with an index argument.
/* list1 consists of [1, 2, 3, 4, 5] and list2 consists of [6, 7, 8, 9] (again)*/
/* I want to merge both lists*/
/* but I want that list2's elements come first*/
list1.addAll(0, list2);
System.out.println(list1);
/* output is [6, 7, 8, 9, 1, 2, 3, 4, 5] */
Notice that
list1.addAll(list2)and
list1.addAll(list1.size(), list2)are the same thing and adding the list2 to the list1 does not effect the content of list2.
Now, it's the removeAll()'s turn. You can remove all the elements of a Collection from a List using this method.
/* list1 consists of [1, 2, 3, 4, 5] and list2 consists of [6, 7, 8, 9] (again)*/
/* I want to remove elements of list2 from list1*/
list1.removeAll(list2);
System.out.println(list1);
/* output is [1, 2, 3, 4, 5]. list1 is intact because there are no elements */
/* of list2 in list1*/
/* list1 consists of [1, 2, 3, 4, 5] and list2 consists of [3, 8, 9, 4]*/
/* I want to remove elements of list2 from list1*/
list1.removeAll(list2);
System.out.println(list1);
/* output is [1, 2, 5]. 3 and 4 which are elements of both list1 and list2 */
/* are removed from list1*/
If you look at the picture above you'll see that we took only the red part of list1 and removed the intersection from it.
The last method of my entry will be retainAll(). retainAll() retains only shared elements of list1 and list2.
/* list1 consists of [1, 2, 3, 4, 5] and list2 consists of [3, 8, 9, 4]*/
/* I want to retain only shared elements of both lists */
list1.retainAll(list2);
System.out.println(list1);
/* output is [3, 4] */
If you take a look at the picture above you'll see that we retain only the intersection which is the blue part of list1. That's all for part 2 secrets of List class part 2.