首先看一個(gè)簡單的示例demo,使用集合(Set)對(duì)列表(List)去重
import java.util.*;
public class Test {
public static void main(String[] args) {
//使用Arrays類構(gòu)造一個(gè)列表
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;
}
}
結(jié)果,在執(zhí)行到①處發(fā)生異常java.lang.UnsupportedOperationException。這就有丶奇怪,為什么能編譯通過,運(yùn)行時(shí)卻發(fā)生異常,難道ArrayList.clear方法內(nèi)部有什么玄機(jī)?追蹤一下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的一個(gè)同名內(nèi)部類——java.util.Arrays.ArrayList。這個(gè)ArrayList同樣繼承了AbstractList,但是并沒有重寫clear、add等方法。所以,在①處調(diào)用的實(shí)際上是父類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方法被重寫,否則會(huì)拋出UnsupportedOperationException異常。
找到了原因,下一個(gè)問題就是怎樣解決。還好java.util.ArrayList提供了接收Collection類型參數(shù)的構(gòu)造方法,而java.util.Arrays.ArrayList繼承自AbstractList,當(dāng)然也是Collection的實(shí)現(xiàn)類,因此我們可以將java.util.Arrays.ArrayList轉(zhuǎn)為java.util.ArrayList,再進(jìn)行下面的clear、add等操作。示例demo如下:
public class Test {
public static void main(String[] args) {
//使用Arrays類構(gòu)造一個(gè)列表,這個(gè)列表的類型是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 + ",");
});
}
/**
* 做類型轉(zhuǎn)換后再使用集合去重
* @param source 需要去重的列表,它的類型是java.util.Arrays.ArrayList
* @return 去重后的列表
*/
public static List<String> duplicateHandler(List<String> source) {
//將參數(shù)轉(zhuǎn)換為java.util.ArrayList類型
source = new ArrayList<>(source);
//去重
Set<String> util = new HashSet<>(source);
source.clear();
source.addAll(util);
return source;
}
}