首先看一個簡單的示例demo绿淋,使用集合(Set)對列表(List)去重
import java.util.*;
public class Test {
public static void main(String[] args) {
//使用Arrays類構造一個列表
String[] sourceArr = {"ii", "aa", "ee", "ii"};
List<String> sourceList = Arrays.asList(sourceArr);
//去重
List<String> result = duplicateHandler(sourceList);
//輸出
result.forEach(item -> {
System.out.print(item + ",");
});
}
/**
* 直接使用集合去重
* @param source 需要去重的列表
* @return 去重后的列表
*/
public static List<String> duplicateHandler(List<String> source) {
Set<String> util = new HashSet<>(source);
source.clear(); //①
source.addAll(util);
return source;
}
}
結果博其,在執(zhí)行到①處發(fā)生異常java.lang.UnsupportedOperationException。這就有丶奇怪植旧,為什么能編譯通過荚醒,運行時卻發(fā)生異常,難道ArrayList.clear方法內(nèi)部有什么玄機隆嗅?追蹤一下Arrays.asList的JDK源碼:
/**
* Returns a fixed-size list backed by the specified array. (Changes to
* the returned list "write through" to the array.) This method acts
* as bridge between array-based and collection-based APIs, in
* combination with {@link Collection#toArray}. The returned list is
* serializable and implements {@link RandomAccess}.
*
* <p>This method also provides a convenient way to create a fixed-size
* list initialized to contain several elements:
* <pre>
* List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");
* </pre>
*
* @param <T> the class of the objects in the array
* @param a the array by which the list will be backed
* @return a list view of the specified array
*/
@SafeVarargs
@SuppressWarnings("varargs")
public static <T> List<T> asList(T... a) {
return new ArrayList<>(a);
}
/**
* @serial include
*/
private static class ArrayList<E> extends AbstractList<E>
implements RandomAccess, java.io.Serializable
{
private static final long serialVersionUID = -2764017481108945198L;
private final E[] a;
ArrayList(E[] array) {
a = Objects.requireNonNull(array);
}
@Override
public int size() {
return a.length;
}
@Override
public Object[] toArray() {
return a.clone();
}
@Override
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
int size = size();
if (a.length < size)
return Arrays.copyOf(this.a, size,
(Class<? extends T[]>) a.getClass());
System.arraycopy(this.a, 0, a, 0, size);
if (a.length > size)
a[size] = null;
return a;
}
@Override
public E get(int index) {
return a[index];
}
@Override
public E set(int index, E element) {
E oldValue = a[index];
a[index] = element;
return oldValue;
}
@Override
public int indexOf(Object o) {
E[] a = this.a;
if (o == null) {
for (int i = 0; i < a.length; i++)
if (a[i] == null)
return i;
} else {
for (int i = 0; i < a.length; i++)
if (o.equals(a[i]))
return i;
}
return -1;
}
@Override
public boolean contains(Object o) {
return indexOf(o) != -1;
}
@Override
public Spliterator<E> spliterator() {
return Spliterators.spliterator(a, Spliterator.ORDERED);
}
@Override
public void forEach(Consumer<? super E> action) {
Objects.requireNonNull(action);
for (E e : a) {
action.accept(e);
}
}
@Override
public void replaceAll(UnaryOperator<E> operator) {
Objects.requireNonNull(operator);
E[] a = this.a;
for (int i = 0; i < a.length; i++) {
a[i] = operator.apply(a[i]);
}
}
@Override
public void sort(Comparator<? super E> c) {
Arrays.sort(a, c);
}
}
驚喜的發(fā)現(xiàn):
Arrays.asList返回并的并不是我們熟悉的java.util.ArrayList,而是Arrays的一個同名內(nèi)部類——java.util.Arrays.ArrayList侯繁。這個ArrayList同樣繼承了AbstractList胖喳,但是并沒有重寫clear、add等方法贮竟。所以丽焊,在①處調(diào)用的實際上是父類AbstractList的clear方法,然后我們看父類的JDK源碼:
/**
* Removes all of the elements from this list (optional operation).
* The list will be empty after this call returns.
*
* <p>This implementation calls {@code removeRange(0, size())}.
*
* <p>Note that this implementation throws an
* {@code UnsupportedOperationException} unless {@code remove(int
* index)} or {@code removeRange(int fromIndex, int toIndex)} is
* overridden.
*
* @throws UnsupportedOperationException if the {@code clear} operation
* is not supported by this list
*/
public void clear() {
removeRange(0, size());
}
注意注釋的這一句:Note that this implementation throws an{@code UnsupportedOperationException} unless {@code remove(int index)} or {@code removeRange(int fromIndex, int toIndex)} is overridden.意思是說咕别,除非remove方法或removeRange方法被重寫技健,否則會拋出UnsupportedOperationException異常。
找到了原因惰拱,下一個問題就是怎樣解決雌贱。還好java.util.ArrayList提供了接收Collection類型參數(shù)的構造方法,而java.util.Arrays.ArrayList繼承自AbstractList偿短,當然也是Collection的實現(xiàn)類欣孤,因此我們可以將java.util.Arrays.ArrayList轉為java.util.ArrayList,再進行下面的clear昔逗、add等操作降传。示例demo如下:
public class Test {
public static void main(String[] args) {
//使用Arrays類構造一個列表,這個列表的類型是java.util.Arrays.ArrayList
String[] sourceArr = {"ii", "aa", "ee", "ii"};
List<String> sourceList = Arrays.asList(sourceArr);
//去重
List<String> result = duplicateHandler(sourceList);
//輸出
result.forEach(item -> {
System.out.print(item + ",");
});
}
/**
* 做類型轉換后再使用集合去重
* @param source 需要去重的列表勾怒,它的類型是java.util.Arrays.ArrayList
* @return 去重后的列表
*/
public static List<String> duplicateHandler(List<String> source) {
//將參數(shù)轉換為java.util.ArrayList類型
source = new ArrayList<>(source);
//去重
Set<String> util = new HashSet<>(source);
source.clear();
source.addAll(util);
return source;
}
}