java.util.Arrays.asList使用體會
下面的程式碼執行後
- privatevoid onButtonAsListClick() {
- String[] strArray = new String[] { "aa", "bb" };
- List<String> list = Arrays.asList(strArray);
- try {
- list.add("cc");
- } catch (Exception e) {
- Log.i("AsList", "add failure");
- }
- }
異常發生
原因:
是一個不可變的陣列,所以修改如下:
- privatevoid onButtonAsListClick() {
- String[] strArray = new String[] { "aa", "bb" };
- ArrayList<String> arrayList = new ArrayList<String>();
- arrayList.addAll(Arrays.asList(strArray));
- try {
- arrayList.add("cc");
- } catch (Exception e) {
- Log.i("AsList"
- }
- for (String string : arrayList) {
- Log.i("AsList", string);
- }
- }
輸出結果:
上面的程式碼:
- ArrayList<String> arrayList = new ArrayList<String>();
- arrayList.addAll(Arrays.asList(strArray));
也可改為:
- ArrayList<String> arrayList = new ArrayList<String>(
- Arrays.asList(strArray));
效果一樣。
最近程式碼中需要對兩個陣列求交,想當然便用到了List中的retainAll函式,但要將將陣列轉換成list。程式碼如下:
String[] abc = new String[] { "abc", "acd", "add" };
String[] abd = new String[] {"acd", "cd", "de"};
List<String> abcList = Arrays.asList(abc);
List<String> abdList = Arrays.asList(abd);
abcList.retainAll(abdList);
沒想到執行後卻丟擲了異常:
java.lang.UnsupportedOperationException
at java.util.AbstractList.remove(AbstractList.java:144)
at java.util.AbstractList$Itr.remove(AbstractList.java:360)
at java.util.AbstractCollection.retainAll(AbstractCollection.java:370)
反編譯後才發現原來 Arrays.asList返回的ArrayList並不是java.util.ArrayList,而是在Arrays類中重新定義的一下內部類ArrayList:
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) {
if (array==null)
throw new NullPointerException();
a = array;
}
//.....其它的省略
}
這個ArrayList並沒有重寫remove方法。
修改成如下,問題解決:
String[] abc = new String[] { "abc", "acd", "add" };
String[] abd = new String[] {"acd", "cd", "de"};
List<String> abcList = new ArrayList<String>(Arrays.asList(abc));
List<String> abdList = new ArrayList<String>(Arrays.asList(abd));
abcList.retainAll(abdList);