1. 程式人生 > >Java 陣列轉換成List,然後執行add或remove拋異常UnsupportedOperationException問題的解決

Java 陣列轉換成List,然後執行add或remove拋異常UnsupportedOperationException問題的解決

在使用Arrays.asList()後呼叫add,remove這些method時出現java.lang.UnsupportedOperationException異常。這是由於Arrays.asList() 返回java.util.Arrays$ArrayList, 而不是ArrayList。Arrays$ArrayList和ArrayList都是繼承AbstractList,remove,add等method在AbstractList中是預設throw UnsupportedOperationException而且不作任何操作。ArrayList override這些method來對list進行操作,但是Arrays$ArrayList沒有override remove(),add()等,所以throw UnsupportedOperationException。

例子:

package CloudPanSys_Test;

import java.util.Arrays;
import java.util.List;

public class Spilt {

	public static void main(String[] args) {
		String path = "/root/m/123.txt";
		path = getClientPath(path);

	}

	public static String getClientPath(String svrPath) {

		StringBuilder newpath = new StringBuilder();
		String[] svrPaths = svrPath.split("/");
		List<String> list = Arrays.asList(svrPaths);

		list.remove(0);//執行丟擲異常
		for (String string : list) {
			newpath.append("/" + string);
		}
		return newpath.toString();
	}

}

執行後,丟擲異常如下:

 

解決

使用Iterator,或者轉換為ArrayList

List list = Arrays.asList(svrPaths);
List<String> list2 = new ArrayList<String>(list);
list2.remove(0);

參考

When you call Arrays.asList it does not return a java.util.ArrayList. It returns a java.util.Arrays$ArrayList which is an immutable list. You cannot add to it and you cannot remove from it.
If you want a mutable list built from your array you will have to loop over the array yourself and add each element into the list in turn.
Even then your code won't work because you'll get an IndexOutOfBoundsException as you remove the elements from the list in the for loop. There are two options: use an Iterator which allows you to remove from the list as you iterate over it (my recommendation as it makes the code easier to maintain) or loop backwards over the loop removing from the last one downwards (harder to read).
You are using AbstractList. ArrayList and Arrays$ArrayList are both types of AbstractList. That's why you get UnsupportedOperationException: Arrays$ArrayList does not override remove(int) so the method is called on the superclass, AbstractList, which is what is throwing the exception because this method is not implemented on that class (the reason being to allow you to build immutable subclasses).