Reputation: 3748
This is reg. a requirement where I need to remove an element from List in java. I am getting unsupported exception when I try to remove element from List. Below is the code:
String[] str_array = {"abc","def","ght"};
List<String> results = Arrays.asList(str_array);
String tobeRemovedItem="";
for(int i=0;i<results.size();i++){
if(results.get(i).equalsIgnoreCase(searchString)) {
tobeRemovedItem=results.get(i);
}
}
if(!TextUtils.isEmpty(tobeRemovedItem)) {
results.remove(tobeRemovedItem); // I am getting exception here.
}
Can anyone help me in solving this issue?
Upvotes: 1
Views: 791
Reputation: 109567
Answered already, but now without indirect datastructure of .asList()
List<String> results = new ArrayList<>();
Collections.addAll(results, str_array);
The .asList is backed by the array, hence you can modify the original array be modifying the list. And vice versa you cannot grow or shrink the list, as then the backed array object would need to be exchanged, as arrays are fixed in java.
Upvotes: 1
Reputation: 15334
In general, UnsupportedOperationException
is thrown by the implementation of an interface (or a child class of a class with an abstract method), where the implementor did not want to support that particular method.
That said, to debug these issues in the future, check which implementation you're using - in this case, it's given via the Arrays.asList()
method from the Android sdk. Here you can see it says that it does not support adding or removing of items to the list.
If you must add and remove items, you can wrap the call into the ArrayList implementation of List which does support such modification (as suggested by Banthar and khelwood). The constructor takes a list as input, and copies the elements inside.
Upvotes: 0
Reputation: 59111
The type of list returned by Arrays.asList
does not support the remove
operation. Hence the exception.
You can use the java.util.ArrayList
instead.
List<String> results = new ArrayList<String>(Arrays.asList(str_array));
Upvotes: 2
Reputation: 18320
The size of List returned by Arrays.asList
cannot be changed. Instead you can do:
List<String> results = new ArrayList<>(Arrays.asList(str_array));
Upvotes: 0