Here you can find the source of addFirstAndRemoveOldIfNeed(List
Parameter | Description |
---|---|
dest | a parameter |
src | a parameter |
public static <T> void addFirstAndRemoveOldIfNeed(List<T> dest, List<T> src)
//package com.java2s; import java.util.Arrays; import java.util.HashMap; import java.util.List; public class Main { public static <T> void addFirstAndRemoveOldIfNeed(List<T> dest, List<T> src) { if (dest == null) { return; }/*from w w w .java2 s.co m*/ if (src == null || src.isEmpty()) { return; } removeDuplicate(dest, src); dest.addAll(0, 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)); } }