Java tutorial
//package com.java2s; import java.util.Arrays; import java.util.HashMap; import java.util.List; public class Main { public static <T> void addTailAndRemoveOldIfNeed(List<T> dest, List<T> src) { if (dest == null) { return; } if (src == null || src.isEmpty()) { return; } removeDuplicate(dest, src); if (dest.isEmpty()) { dest.addAll(src); } else { dest.addAll(dest.size(), src); } } @SuppressWarnings("unchecked") public static <T> void removeDuplicate(List<T> dest, List<T> src) { if (dest == null) { return; } if (src == null || src.isEmpty()) { return; } int capacity = dest.size() > src.size() ? dest.size() : src.size(); HashMap<T, Integer> map = new HashMap<T, Integer>(capacity); for (int i = 0; i < dest.size(); i++) { map.put(dest.get(i), i); } T[] oldData = (T[]) dest.toArray(); int length = oldData.length; for (T t : src) { Integer index = map.get(t); if (index != null) { oldData[index] = null; length--; } } T[] removedDuplicate = (T[]) new Object[length]; int index = 0; for (int i = 0; i < oldData.length; i++) { if (oldData[i] != null) { removedDuplicate[index++] = oldData[i]; } } dest.clear(); dest.addAll(Arrays.asList(removedDuplicate)); } }