ITeye博客

List差集

harbey · 2009-07-30 22:48 · Java · Markdown


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

/**
 * List工具类
 * <p>
 *   提供处理List对象的各种方法实现。
 * </p>
 * 
 * @author harbey
 * @version 1.0
 * @since 2009-07-30
 */
public class ListUtil {

	/**
	 * List对象差集
	 * <p>
	 *   使用深复制,不会影响List参数对象。
	 * </p>
	 * @param decList 被减数List对象
	 * @param subList 减数List对象
	 * @return 结果List
	 * @throws IllegalArgumentException
	 */
	public static List<String> plusArrayList(List<String> decList,List<String> subList) throws IllegalArgumentException{
		   
		   if(decList==null || subList==null){
			   throw new IllegalArgumentException();
		   }
	 
			List<String> tempDecList = new ArrayList<String>(new ArrayList(Arrays.asList(new Object[declist.size()])));
			List<String> tempSubList = new ArrayList<String>(new ArrayList(Arrays.asList(new Object[sublist.size()])));
		   
			Collections.copy(tempDecList, decList);
			Collections.copy(tempSubList, decList);
			
			tempDecList.removeAll(tempSubList);
			
		    return tempDecList;
	   }
	   
}

如果 List tempDecList = new ArrayList(decList.size()); 则会报java.lang.IndexOutOfBoundsException错误! 原因: ArrayList iss=new ArrayList(ist.size());does not ensure size, but set the initialize of the internal array.

评论(2)

  1. #2 楼 · paris · 2011-10-11 10:01

    第二行Collections.copy(tempSubList, decList); 后边的参数应该是subList,应该是笔误吧

  2. #1 楼 · zhangyou1010 · 2009-09-23 15:20

    List tempDecList = new ArrayList(decList.size()); 这样写的话tempDecList会初始化decList.size()个null元素,但tempDecList 的size还是0,所以会报错。

    学习了。 :)

评论功能维护中,当前仅展示历史评论。