List删除元素

/**
** List删除元素
** 方法1使用了HashSet
** 方法2需要多层循环
** 貌似方法1快些
**/
package net;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

public class MyList {

	public static void main(String[] args) {
		MyList myList = new MyList();

		long start = System.currentTimeMillis();
		myList.testCase2();
		long now = System.currentTimeMillis();
		System.err.println(now - start);

		start = System.currentTimeMillis();
		myList.testCase1();
		now = System.currentTimeMillis();
		System.err.println(now - start);
	}

	public void testCase2() {
		List<Name> list = initData();

		List<String> exclude = new ArrayList<String>();
		exclude.add("1");
		exclude.add("5");
		exclude.add("6");

		List<Name> delete = new ArrayList<Name>();
		for (String s : exclude) {
			for (Name n : list) {
				if (n.id.equals(s)) {
					delete.add(n);
				}
			}
		}

		list.removeAll(delete);

		// displayResult(list);
	}

	public void testCase1() {
		List<Name> list = initData();

		// 1,5,6
		List<String> exclude = new ArrayList<String>();
		exclude.add("1");
		exclude.add("5");
		exclude.add("6");

		HashSet<String> hs = new HashSet<String>();
		for (String s : exclude) {
			hs.add(s);
		}

		Iterator<Name> it = list.iterator();
		while (it.hasNext()) {
			Name n = it.next();
			if (!hs.add(n.id)) {
				it.remove();
			}
		}

		// displayResult(list);
	}

	public List<Name> initData() {
		List<Name> list = new ArrayList<Name>();
		for (int i = 0; i < 10; i++) {
			Name n = new Name();
			n.id = "" + i;
			list.add(n);
		}
		return list;
	}

	public void displayResult(List<Name> list) {
		for (Name n : list) {
			System.err.println(n.id);
		}
	}
}

class Name {
	String id;
	String name;
}

你可能感兴趣的:(list)