码迷,mamicode.com
首页 > 其他好文 > 详细

【DataStructure】The difference among methods addAll(),retainAll() and removeAll()

时间:2014-07-13 16:43:15      阅读:268      评论:0      收藏:0      [点我收藏+]

标签:struts   structure   methods   java   

  In the Java collection framework, there are three similar methods, addAll(),retainAll() and removeAll().  addAll(), the retainAll(), and the removeAll()methods are equivalent to the set theoretic union,  intersection, and complement operators, respectively. These are illustrated in the following picture.

bubuko.com,布布扣

In my local machine, just for these methods, I made a test for them respectively. 

package com.albertshao.ds.set;

import static org.junit.Assert.assertEquals;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import org.junit.After;
import org.junit.Test;

public class TestCollectionsMethods {

	List<String> listA = null;
	List<String> listB = null;
	List<String> result = new ArrayList<String>();
	List<String> testList = new ArrayList<String>();
	
	@Test
	public void testAddAll() {
		listA = Arrays.asList("Apple","Blanana","Grape");
		listB = Arrays.asList("Apple","Orange","Pear");
		Collections.addAll(testList,"Apple","Blanana","Grape","Apple","Orange","Pear");
		result.addAll(listA);
		result.addAll(listB);
		assertEquals(testList, result);
	}

	@Test
	public void testRetainAll() {
		listA = Arrays.asList("Apple","Blanana","Grape");
		listB = Arrays.asList("Apple","Orange","Pear");
		Collections.addAll(testList,"Apple");
		result.addAll(listA);
		result.retainAll(listB);
		assertEquals(testList, result);
		
	}
	
	@Test
	public void testRemoveAll() {
		listA = Arrays.asList("Apple","Blanana","Grape");
		listB = Arrays.asList("Apple","Orange","Pear");
		Collections.addAll(testList,"Blanana","Grape");
		result.addAll(listA);
		result.removeAll(listB);
		assertEquals(testList, result);
	}
	
	@After
	public void testPrint()
	{
		System.out.println("-----------------------");
		if(result != null && !result.isEmpty())
		{
			for(String str: result)
			{
				System.out.println(str);
			}
		}
		System.out.println("-----------------------");
	}

}

The result of execution is as follows: 

bubuko.com,布布扣


Hope it‘s beneficial to you 

【DataStructure】The difference among methods addAll(),retainAll() and removeAll(),布布扣,bubuko.com

【DataStructure】The difference among methods addAll(),retainAll() and removeAll()

标签:struts   structure   methods   java   

原文地址:http://blog.csdn.net/sxb0841901116/article/details/37730719

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!